【发布时间】:2010-11-27 19:25:57
【问题描述】:
我建立了以下关系:
A HABTM B
B belongsTo C
C hasMany B
现在,对于给定的 A,我需要所有带有 B 的 C。我可以编写 SQL 查询,但是正确的 CakePHP 方式是什么?我在哪个模型上调用什么方法,使用什么参数?
【问题讨论】:
标签: php cakephp python-datamodel
我建立了以下关系:
A HABTM B
B belongsTo C
C hasMany B
现在,对于给定的 A,我需要所有带有 B 的 C。我可以编写 SQL 查询,但是正确的 CakePHP 方式是什么?我在哪个模型上调用什么方法,使用什么参数?
【问题讨论】:
标签: php cakephp python-datamodel
我会想到“可包含”行为 (http://book.cakephp.org/view/474/Containable)...在查找相关数据方面提供了很大的控制权。
【讨论】:
我会接受 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。
【讨论】:
这可能有效
$this->C->find('all',
array('conditions'=>array('id'=>'someword','B.aid'=>$a.id)));
【讨论】:
$this->A->find(
'first',
array('conditions'=>array('id'=>'someword'),
'recursive'=>2)
);
喜欢这样吗?
【讨论】:
$this->A->B->C 与 $this->C 相同,对A 的条件没有帮助。