【问题标题】:how to make left join between two tables without relation in doctrine 1.2如何在学说1.2中没有关系的两个表之间进行左连接
【发布时间】:2013-06-19 11:47:29
【问题描述】:
我有两张桌子。
Table invitations
Columns:
id email created_at
Table orders
Columns:
id amount email created_at
我需要创建一个 DQL 以从邀请表中选择所有字段,然后在电子邮件中使用订单表中的所有记录计数进行左连接
注意我需要查看结果,所以我需要对结果进行分页,两个表之间没有关系
【问题讨论】:
标签:
symfony-1.4
doctrine-1.2
【解决方案1】:
创建 DQL 查询:
$q = Doctrine_Query::create()
->select('i.*')
->from('invitations i')
->leftJoin('i.orders o ON i.email=o.email')
;
您可以添加更多条件:
->having('COUNT(email) > 10')
->groupBy('i.email')
->orderBy('i.email ASC');
打印结果 SQL 查询以检查错误:
echo $q->getSqlQuery();
执行 DQL 查询:
$vrows = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //For speed use Hydrate_Array, read the documentation about hydrating methods. If not specified you will get a list of records objects.
另一种方法就像 ilSavo 和 Michal 所说,创建您自己的查询或在您的架构中写入这两个表之间的关系。
第三种方法是直接将 SQL 原始查询发送到数据库,而不使用 ORM 原则:
$oConnection = Doctrine_Manager::getInstance()->getConnectionForComponent($sModuleName);
$vrecords = $oCurrentConnection->fetchAssoc($sSQLquery);
为了对结果进行分页,请查看here。
记得使用 try 和 catch 来获取异常。