我设置了以下关系:

A HABTM B
B belongsTo C
C hasMany B

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

有帮助吗?

解决方案

我会选择Aziz的答案并简单地处理数据。如果你需要C作为主要模型,你将不得不做一些解决方法。蛋糕在相关模型上的条件并不是非常好,特别是对于删除的第三代表兄弟的查询。它通常只对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实际上可能是最干净的方法。

编辑:

或者,您可以重新绑定您的动态关联使它们具有多个/属于关系,最有可能使用A和B的连接表/模型。这可能使您更容易使用相关模型的条件,但获取Cs仍然很棘手当条件在A时。

其他提示

$this->A->find(
   'first', 
   array('conditions'=>array('id'=>'someword'), 
   'recursive'=>2)
);
像这样?

这可能有效

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

我想到“可以包含”行为( http://book.cakephp.org/view/474/Containable ) ...对发现相关数据给予了很多控制。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top