我有什么:
"A" HABTM "C" HABTM "A" through join table "B"
"A" hasMany "B" belongsTo "A"
"C" is ordered by a "B" field
我想要的是什么:
// result:
[0] => array(
A => array( /* single model's fields I still need*/ ),
C => array(
[0] => array( C.field1, C.field2, ... /* Model C fields*/ ),
[1] => array( C.field1, C.field2, ... )
)
)
我尝试了什么:
// this gives me data I don't need:
A->find('all', array( 'conditions' => array( 'id' => $id ) ) )
// result:
[0] => array(
A => array( /* single model's fields I need*/ ),
B => array( /* I DON'T NEED */
[0] => array( ... )
[1] => array( /* ... etc, tons records I don't need */ )
),
C => array(
[0] => array( C.field1, C.field2, ... /* I need these fields*/
[B] => array( /* I DON'T NEED */ )
),
[1] => array( C.field1, C.field2, ... )
[B] => array( /* ... etc, each has a model B I don't need ... */)
)
)
)
使用Containable,我可以减少相当多的查询,但仍有相关的模型:
// this is a little better
A->find('all', array(
'conditions' => array( 'id' => $id ),
'contain' => array( 'C' )
))
// result:
[0] => array(
A => array( /* single model's fields I still need*/ ),
C => array(
[0] => array( C.field1, C.field2, ... /* I still need Model C fields*/
[B] => array( /* I still DON'T need this Model's fields */ )
),
[1] => array( C.field1, C.field2, ...
[B] => array( /* ... still has unneeded model B */)
)
)
)
NB1 :我已阅读本书中的this,this和this,以及this和{{3 }}
NB2 :我也试过
C->recursive = -1 // no effect
C->unbindModel(array('hasAndBelongsToMany'=>A)) // no effect
A->find('all', array( // not what I want, but it's still
'conditions' => array('id' => $id), // odd that this doesn't filter C's
'contain' => array('A.B'))); // fields out. same as second result
A->find('all', array( // also not what I want, but it's
'conditions' => array('id' => $id), // weird that this doesn't filter B's
'contain' => array('A.B.field'))); // fields at all;
答案 0 :(得分:1)
ContainableBehavior将自动返回映射结果所需的字段。
从您已阅读的page引用:
$this->Post->find('all', array('contain' => 'Comment.author'));
... // data returned:
[Comment] => Array
(
[0] => Array
(
[author] => Daniel
[post_id] => 1
)
...
如您所见,Comment数组 仅包含作者字段(加号 CakePHP需要的post_id 映射结果)。
对于HABTM关系,将返回具有关联外键的连接模型,因为Containable需要a_id
和c_id
字段。我的建议是忽略它并采取你需要的值。如果您愿意,您可以查看joins,因为Containable有时会多次查询数据库。但是,关联模型的数据不会像包含的那样很好地返回。