草庐IT

php - 如何为嵌套关系构建适当的 CakePHP 查询

coder 2023-10-06 原文

我是 CakePHP 的新手,我正在尝试为结果构建复杂的查询。这太痛苦了。也许有人可以帮我解决这个问题。 我用的是cake 2.7

我有两个具有 3 个关系(多对多)的表。 邻域多边形。 案例看起来像这样 Neighbourhood 有许多 Neighbourhoods 并且它也属于许多 Neighbourhoods。此外,Neighbourhood 有许多 Polygons 并且 Polygon 属于许多 Neighbourhoods

Neighbourhood 表包含 2 个字段 namezip。我从用户那里得到的是 zip code

现在我想要的是: 我想从 Neighbourhood 获取所有 Polygons,它是 Neighbours。其中 Neighbourhood.zip = 由用户定义

我该怎么做?我应该编写自定义查询还是将过程分成更小的步骤?我整天都在为此奋斗。

这是模型关系的样子:

class Neighbourhood extends AppModel
{
    var $hasAndBelongsToMany = array(
        'Neighbourhoods' => array(
            'className' => 'Neighbourhood',
            'joinTable' => 'neighbourhoods_neighbours',
            'foreignKey' => 'neighbourhood_id',
            'associationForeignKey' => 'neighbour_id',
            'unique' => false
        ),
        'Polygon' => array(
            'className' => 'Polygon',
            'joinTable' => 'neighbourhoods_polygons',
            'foreignKey' => 'neighbourhood_id',
            'associationForeignKey' => 'polygon_id',
            'unique' => false
        ),
    );
}


class Polygon extends AppModel
{
    var $hasAndBelongsToMany = array(
        'Neighbours' => array(
            'className' => 'Neighbourhood',
            'joinTable' => 'neighbourhoods_polygons',
            'foreignKey' => 'polygon_id',
            'associationForeignKey' => 'neighbourhood_id',
            'unique' => false,
        )
    );
}

最佳答案

您需要在您的模型中启用可包含的行为,或者在您的应用模型中设置它后更好。

public $actsAs = array('Containable');

然后开始构建您的查询,例如

$conditions = array(
    'conditions' => array('id' => '123'),
    'contain' => array(
        'Neighbourhood'=>array(
              'conditions' => array('Neighbourhood.id' => '123')
         )
     ),
     // or even joins
     'joins' => array(
          array(
                    'table' => $this->getTableName('default', 'neighbourhoods'),
                    'alias' => 'Neighbourhood',
                    'type' => 'RIGHT', // OR LEFT
                    'conditions' => array(
                        'Neighbourhood.id = Polygon.neighbourhood_id',
                        'Neighbourhood.deleted' => 0,
                    )
          )
     )
 );

$polygons = $this->Polygon->find('all', $conditions);

如果您认为这还不够(为了执行更复杂的查询),那么您需要构建查询语句。例如从多边形模型运行查询:

    $dbo = $this->getDataSource();
    $query = $dbo->buildStatement(
            array(
                'fields' => array(
                    'Polygon.name AS polygon_name', 'Polygon.size',
                    'Neighbourhood.name AS neighbourhood_name', 'Neighbourhood.lat', 
                    'IF( Neighbourhood.created > DATE_SUB(NOW(), INTERVAL 1 DAY) , 1 , 0) AS new_neighbourhood'  
                ), 
                'table' => $dbo->fullTableName($this),
                'alias' => 'Polygon',
                'limit' => null,
                'offset' => null,
                'joins' => array(
                    array(
                        'table' => $this->getTableName('default', 'neighbourhoods'),
                        'alias' => 'Neighbourhood',
                        'type' => 'LEFT',
                        'conditions' => array(
                            'Neighbourhood.id = Polygon.neighbourhood_id',
                        ), 
                        'order' => 'Neighbourhood.name ASC',
                    ),
                    ....
                 ), 
                'conditions' => $conditions,
                'group' => 'Polygon.name',
                'order' => 'Polygon.name ASC',
           ),
           $this
     );

 $polygons = $this->query($query);

如果你认为这还不够,那么你必须像这样唱奇异恩典..

$polygons = $this->query("Here your sql query");

 debug($polygons);

关于php - 如何为嵌套关系构建适当的 CakePHP 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32051217/

有关php - 如何为嵌套关系构建适当的 CakePHP 查询的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  4. ruby - 如何为 emacs 安装 ruby​​-mode - 2

    我刚刚为fedora安装了emacs。我想用emacs编写ruby。为ruby​​提供代码提示、代码完成类型功能所需的工具、扩展是什么? 最佳答案 ruby-mode已经包含在Emacs23之后的版本中。不过,它也可以通过ELPA获得。您可能感兴趣的其他一些事情是集成RVM、feature-mode(Cucumber)、rspec-mode、ruby-electric、inf-ruby、rinari(用于Rails)等。这是我当前用于Ruby开发的Emacs配置:https://github.com/citizen428/emacs

  5. ruby-on-rails - 在 Rails 和 ActiveRecord 中查询时忽略某些字段 - 2

    我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr

  6. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

  7. ruby - 模块嵌套代码风格偏好 - 2

    我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的

  8. ruby-on-rails - 使用回形针的嵌套形式 - 2

    我有一个名为posts的模型,它有很多附件。附件模型使用回形针。我制作了一个用于创建附件的独立模型,效果很好,这是此处说明的View(https://github.com/thoughtbot/paperclip):@attachment,:html=>{:multipart=>true}do|form|%>posts中的嵌套表单如下所示:prohibitedthispostfrombeingsaved:@attachment,:html=>{:multipart=>true}do|at_form|%>附件记录已创建,但它是空的。文件未上传。同时,帖子已成功创建...有什么想法吗?

  9. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

  10. ruby - Rails 关联 - 同一个类的多个 has_one 关系 - 2

    我的问题的一个例子是体育游戏。一场体育比赛有两支球队,一支主队和一支客队。我的事件记录模型如下:classTeam"Team"has_one:away_team,:class_name=>"Team"end我希望能够通过游戏访问一个团队,例如:Game.find(1).home_team但我收到一个单元化常量错误:Game::team。谁能告诉我我做错了什么?谢谢, 最佳答案 如果Gamehas_one:team那么Rails假设您的teams表有一个game_id列。不过,您想要的是games表有一个team_id列,在这种情况下

随机推荐