【发布时间】:2012-08-18 18:35:01
【问题描述】:
我正在使用 CakePHP 2.1
让我们声明我有以下模型和关系:PostsbelongsTo EditionPostsHABTM EditorsPostsHABTM Tags
我从PostsController 推理,我想找到属于某个Edition 的所有Posts,并且Editor.id=55 是相关的,Tag.id=33 是相关的。
我发现了许多示例,其中基于 HABTM 关系上的条件查找Posts 是通过“反转”Editor 的查找方向和原因来完成的。
$this->Editor->find('all',
array(
'conditions'=>array('Editor.id'=>55),
'contain'=>array('Post')
)
);
不幸的是,这在这里不起作用,因为我想设置多个 HABTM 关系。
同样使用 contain 也不起作用,因为它只切断了一个分支 (editors),但无助于过滤它的父级 (posts)。
我该如何解决这个问题?
我可能需要诉诸临时加入吗?如果是这样,有人可以大致解释我采取什么方法吗?
编辑: 一些伪代码以说明我想要实现的目标:
$this->Post->find('all',
array('conditions'=>array(
'Edition.id'=>4,
// start pseudo code
'Post.Editor' => 'has at least one related editor with id=55',
'Post.Tag' => 'has at least one related tag with id=33',
)
)
);
亲切的问候, 巴特
编辑解决方案: 在@RichardAtHome 之后,我创建了下面的解决方案。没有(还)使用多个连接条件,但这似乎没有必要:
// Paginate over Cards that belong to current Subscription (belongsTo) AND the User is related to as an Editor (HABTM)
$this->paginate = array(
'fields' => array('id','title','workingtitle','attachment_count','subscription_id'),
'joins' => array(
// create Editor-join
array(
'table' => 'cards_users',
'alias' => 'Editor',
'type' => 'left',
'conditions' => array(
'Editor.card_id = Card.id'
)
),
array(
'table' => 'users',
'alias' => 'User',
'type' => 'left',
'conditions'=> array(
'User.id = Editor.user_id'
)
)
),
'conditions' => array(
'OR' => array(
// is Card in current subscription? (straightforward condition)
array('Card.subscription_id',$subscription_id),
// is current User assigned as Editor? (condition works with join above)
array('User.id' => $user['id'])
)
),
'limit' => 10
);
【问题讨论】:
-
你真正想要什么?给出你想要的一些粗略的代码图。
-
@arun-jain 我添加了一些伪代码,是否足够清楚?
标签: cakephp cakephp-2.0 conditional-statements has-and-belongs-to-many multiple-conditions