CakePHP 和 HABTM 模型限制错误 [英] CakePHP and HABTM Model Limit Error
问题描述
我有一系列具有AndBelongsToMany Media 模型的Post 模型.在 Post 模型内部的某些函数调用中,我不需要检索整个 Media 模型列表.但是,当我使用以下代码时:
I've got a series of Post models that hasAndBelongsToMany Media models. In certain function calls inside of the Post model, I don't need to retrieve the entire list of Media models. However, when I use the following code:
$this->unbindModel( array('hasAndBelongsToMany' => array('Media')) );
// Rebind to get only the fields we need:
$this->bindModel(
array('hasAndBelongsToMany' => array(
'Media' => array(
'className' => 'Media',
'joinTable' => 'media_posts',
'foreignKey' => 'post_id',
'associationForeignKey' => 'media_id',
'limit' => 1,
'fields' => array('Media.type', 'Media.path', 'Media.title')
)
)
)
);
$this->find('all', $params);
此限制仅适用于第一个检索到的 Post 模型之一,并且所有后续 Post 模型都没有关联的媒体:
This limit only works on one of the first retrieved Post model and all following Post models have no associated Media:
Array
(
[0] => Array
(
[Profile] => Array
(
)
[Media] => Array
(
[0] => Array
(
[type] => photo
[path] => ''
[title] => ''
)
)
)
[1] => Array
(
[Profile] => Array
(
)
[Media] => Array
(
)
)
)
任何建议都会很棒.谢谢!
Any suggestions would be great. Thanks!
推荐答案
为什么不使用 containable行为
// you would probably want the next line in the app_model ot be able to use it with all models
$this->Post->actsAs = array('Containable')
$params['conditions'] = array(
);
$params['contain'] = array(
'Media' => array(
'fields' => array(
'type', 'path', 'title'
),
'limit' => 1
)
);
$this->Post->find('all', $params);
<小时>
刚试过,得到了这个 sql (Module <-> Tag):
Just tried that and got this sql (Module <-> Tag):
SELECT `Module`.`id` FROM `modules` AS `Module` WHERE 1 = 1
和
SELECT `Tag`.`id`, `ModulesTag`.`module_id`, `ModulesTag`.`tag_id`
FROM `tags` AS `Tag`
JOIN `modules_tags` AS `ModulesTag`
ON (`ModulesTag`.`module_id` IN (1, 2, 3, 4) AND `ModulesTag`.`tag_id` = `Tag`.`id`)
WHERE `Tag`.`belongs_to` = 'Module'
ORDER BY `Tag`.`name` ASC
LIMIT 1
显然不能返回想要的结果,因为您必须对每个模块结果进行查询(这又会导致太多查询).
obviously that cannot return the wanted result, as you would have to do a query for each Module result (which then again would result in way too many queries).
作为结论,我会返回所有标签(在我的示例中),因为太多结果行的开销比太多查询的开销要好..
As a conclusion I would return all Tags (in my example) as the overhead in too many result rows is better than the overhead of too many queries..
这篇关于CakePHP 和 HABTM 模型限制错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!