如何在Propel中多次将表连接到自身?

时间:2014-03-05 16:47:28

标签: php mysql join propel

我在this answer中尝试了解决方案,但它没有用。它产生了以下SQL:

SELECT user.id AS `Id`, user.name AS `Name`,
  AS `ReferralUser.Id`,  AS `ReferralUser.Name`
FROM `ReferralUser` INNER JOIN `account` ON (ReferralUser.id=account.id)

请注意,ReferralUser不是我的数据库中的表,它应该是别名。

我需要至少两次加入一张桌子,但将来可能更多。我目前的代码:

$q = \UserQuery::create();
$q->select(array('Id', 'Name', 
    'ReferralUserRelation.Id', 'ReferralUserRelation.Name', 
    'CreatorUserRelation.Id', 'CreatorUserRelation.Name'));

$q->join('ReferralUserRelation');
$q->join('CreatorUserRelation');

$q->find();

这导致以下SQL:

SELECT user.id AS `Id`, user.name AS `Name`, user.id AS `ReferralUserRelation.Id`, 
user.name AS `ReferralUserRelation.Name`, `user.id` AS `CreatorUserRelation.Id`, 
`user.name` AS `CreatorUserRelation.Name` FROM `user`  
INNER JOIN `user` ON (user.id=user.referral_user_id) 
INNER JOIN `user` ON (user.id=user.creator_user_id) 

这在Propel中甚至可能吗?

1 个答案:

答案 0 :(得分:1)

我建议使用表别名和ActiveQuery API(请参阅http://propelorm.org/reference/model-criteria.html#table-aliases)。例如,如果User表与自身有Supervisor的关系:

// Table aliases are mostly useful to join the current table,
// or to handle multiple foreign keys on the same column
$employee = EmployeeQuery::create('e')
  ->innerJoin('e.Supervisor s')
  ->where('s.Name = ?', 'John')
  ->find();