我最近升级到Propel 1.5,并开始在Criteria上使用它的查询功能。但我有一个无法翻译的查询 - 一个有多个条件的左连接:
SELECT * FROM person
LEFT JOIN group_membership ON
person.id = group_membership.person_id
AND group_id = 1
WHERE group_membership.person_id is null;
其目的是找到不在指定组中的所有人。以前我使用以下代码来完成此任务:
$criteria->addJoin(array(
self::ID,
GroupMembershipPeer::GROUP_ID,
), array(
GroupMembershipPeer::PERSON_ID,
$group_id,
),
Criteria::LEFT_JOIN);
$criteria->add(GroupMembershipPeer::PERSON_ID, null, Criteria::EQUAL);
我考虑过对该组中的所有人执行查询,获取主键并在阵列上添加NOT IN
,但似乎没有一种特别简单的方法可以从查找中获取主键,它似乎并不优雅。
关于codenugget.org的文章详细介绍了如何为加入添加额外条件,我尝试过:
$result = $this->leftJoin('GroupMembership');
$result->getJoin('GroupMembership')
->addCondition(GroupMembershipPeer::GROUP_ID, $group->getId());
return $result
->useGroupMembershipQuery()
->filterByPersonId(null)
->endUse();
不幸的是,'useGroupMembershipQuery'会覆盖左连接。为了解决这个问题,我尝试了以下代码:
$result = $this
->useGroupMembershipQuery('GroupMembership', Criteria::LEFT_JOIN)
->filterByPersonId(null)
->endUse();
$result->getJoin('GroupMembership')
->addCondition(GroupMembershipPeer::GROUP_ID, $group->getId());
return $tmp;
由于某种原因,这导致由于某种原因执行交叉连接:
SELECT * FROM `person`
CROSS JOIN `group_membership`
LEFT JOIN group_membership GroupMembership ON
(person.ID=GroupMembership.PERSON_ID
AND group_membership.GROUP_ID=3)
WHERE group_membership.PERSON_ID IS NULL
有没有人知道为什么会这样做,或者如何在Propel 1.5中成功执行此连接,而不必再诉诸Criteria?
答案 0 :(得分:8)
Propel 1.6支持使用addJoinCondition()
加入多个条件。如果您更新Symfony插件,或移至sfPropelORMPlugin,您可以利用它。然后可以像这样编写查询:
return $this
->leftJoin('GroupMembership')
->addJoinCondition('GroupMembership', 'GroupMembership.GroupId = ?', $group->getId())
->where('GroupMembership.PersonId IS NULL');