【问题标题】:Querying data based on 3rd level relationship in CakePHPCakePHP中基于三级关系查询数据
【发布时间】:2010-11-27 19:25:57
【问题描述】:

我建立了以下关系:

A HABTM B
B belongsTo C
C hasMany B

现在,对于给定的 A,我需要所有带有 B 的 C。我可以编写 SQL 查询,但是正确的 CakePHP 方式是什么?我在哪个模型上调用什么方法,使用什么参数?

【问题讨论】:

    标签: php cakephp python-datamodel


    【解决方案1】:

    我会想到“可包含”行为 (http://book.cakephp.org/view/474/Containable)...在查找相关数据方面提供了很大的控制权。

    【讨论】:

      【解决方案2】:

      我会接受 Aziz 的回答,并简单地处理传入的数据。但是,如果您需要 C 作为主要模型,则必须采取一些解决方法。 Cake 在相关模型上的条件还不是非常好,尤其是在删除了 3rd cousins 类型的查询时。它通常只对 belongsTo 或 hasMany 关系进行实际的 JOIN 查询;但不是在 HABTM 关系上,而是在单独的查询中获得的那些关系。这意味着您不能在相关的 HABTM 模型中包含条件。

      那么你最好的选择可能是这样的:

      // get related records as usual with the condition on A, limit to as little data as necessary
      $ids = $this->A->find('first', array(
          'conditions' => array('A.id' => 'something'), 
          'recursive'  => 2,
          'fields'     => array('A.id'),
          'contain'    => array('B.id', 'B.c_id', 'B.C.id') // not quite sure if B.C.id works, maybe go with B.C instead
      ));
      
      // find Cs, using the ids we got before as the condition
      $Cs = $this->C->find('all', array(
          'conditions' => array('C.id' => Set::extract('/B/C/id', $ids)),
          'recursive   => 1
      );
      

      请注意,这会产生大量查询,因此它并不是真正的最佳解决方案。编写自己的 SQL 实际上可能是最简洁的方式。

      编辑:

      或者,您可以re-bind your associations on the fly 使它们成为 hasMany/belongsTo 关系,最有可能使用 A 和 B 的连接表/模型。这可能使您能够更轻松地在相关模型上使用条件,但获取仍然很棘手条件为 A 时的 Cs。

      【讨论】:

        【解决方案3】:

        这可能有效

        $this->C->find('all',
        array('conditions'=>array('id'=>'someword','B.aid'=>$a.id)));
        

        【讨论】:

          【解决方案4】:
          $this->A->find(
             'first', 
             array('conditions'=>array('id'=>'someword'), 
             'recursive'=>2)
          );
          

          喜欢这样吗?

          【讨论】:

          • 不,将C放在A下的每个B下。我首先需要C,B列表,B有A作为条件。
          • 为什么要找到'first'??对于给定的 A,不应该找到“全部”吗,所有带有 B 的 C 都是必需的。
          • @Adit:这会找到一个第一个)A和所有附加的B和C。跨度>
          • $this->A->B->C->find('... 它将收集与C相关的模型
          • @Aziz: $this->A->B->C$this->C 相同,对A 的条件没有帮助。
          猜你喜欢
          • 1970-01-01
          • 2020-05-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-30
          • 1970-01-01
          相关资源
          最近更新 更多