我有一点时间将以下原始MySQL查询转换为学说1.2:
已经过测试并且运行良好SELECT
r.name AS regionname,
s.name AS statename
FROM
job j
LEFT JOIN
community c ON c.id = j.community_id
LEFT JOIN
state s ON s.id = c.state_id
LEFT JOIN
region r ON r.id = s.region_id
WHERE
r.id = 1
这不起作用:
$q = Doctrine_Query::create()
->select('r.name AS regionname', 's.name AS statename')
->from('job j')
->leftJoin('community c ON c.id = j.community_id')
->leftJoin('state s ON s.id = c.state_id')
->leftJoin('region r ON r.id = s.region_id')
->where('r.id = 1')
->execute();
这是我的数据库结构,如果有用的话:
job:
columns:
id
community_id
relations:
community: local_key: community_id, foreign_key: id, foreignAlias: Communitys
community:
columns:
id
state_id
relations:
state: local_key: state_id, foreign_key: id, foreignAlias: States
state:
columns:
id
name
region_id
relations:
region: local_key: region_id, foreign_key: id, foreignAlias: Regions
region:
columns:
id
name
答案 0 :(得分:0)
我也注意到了同样的事情。在Doctrine 1.2中进行连接与mysql有点不同。要进行连接,您必须利用Doctrine在您的工作类中的每个组件中创建的关系。
您可以查看作业的基类,了解我正在谈论的这些关系。在setup方法中,它们看起来像这样,例如作业表中的社区外键id:
$this->hasOne('community as Communitys', array(
'local' => 'community_id',
'foreign' => 'id'));
回到你的问题,要进行连接,你必须引用外键所属的表的别名。例如,如果您想使用别名社区加入社区表:
->leftJoin('j.Community')
而不是
community c ON c.id = j.community_id
请注意,我没有说id加入,因为在Doctrine 1.2中已经隐含了。但是,您可以选择加入其他内容。
同样,如果您之前加入的表需要加入其他表,那么他们必须拥有外键
1.在当前查询中使用别名 2.引用其基类中所述的组件。
所以你说你想在当前查询中加入社区到你应该这样做的状态
// join job and community first
->from('job j')
->leftJoin('j.Community c')
// join community to state since they are the ones that are related
->leftjoin('c.States s')
从这里,我希望你能看到这种模式。在一天结束时,如果你看一下,加入的想法与原始sql仍然相同,唯一的区别是语法:
SQL语法:
LEFT JOIN
community c ON c.id = j.community_id
DQL语法:
->leftJoin('j.Community c')
无论如何要回答你的问题,这里是联系应该如何完成:
$q = Doctrine_Query::create()
->select('*')
->from('job j')
->leftJoin('j.Community c')
->leftJoin('c.State s')
->leftJoin('s.Region r')
->where('r.id = 1')
->execute();