How do I join a table to itself multiple times in Propel?

对着背影说爱祢 提交于 2019-12-12 04:44:20

问题


I tried the solution in this answer, but it did not work. It resulted in the following 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)

Note that ReferralUser is not a table in my database, it was meant to be the alias.

I need to join a table to itself at least two times, but possibly more in the future. My current code:

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

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

$q->find();

Which results in the following 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) 

Is this even possible in Propel?


回答1:


I recommend using table aliases and the ActiveQuery API (see http://propelorm.org/reference/model-criteria.html#table-aliases). For instance, if the User table has a Supervisor relationship to itself:

// 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();


来源:https://stackoverflow.com/questions/22203960/how-do-i-join-a-table-to-itself-multiple-times-in-propel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!