Laravel Query Builder加入与RAW不同

时间:2017-10-19 13:19:47

标签: php mysql laravel

我正在使用laravel Query Builder从mysql db连接两个表 当我在shell中使用原始查询

SELECT * from parent_accounts
LEFT JOIN child_accounts on parent_accounts.account_id=child_accounts.parent_id

结果

enter image description here

使用laravel Query Builderas时如下

 $accounts=\DB::table('parent_accounts as p')->join('child_accounts as c','p.account_id','=','c.parent_id')->select('p.name AS parent','c.name as name','c.account_id as account_id','c.parent_id as parent_id')->get();

我从来没有得到第4行,如果我首先使用带有child_accounts的左连接,那不是那个结果吗?

2 个答案:

答案 0 :(得分:1)

尝试使用查询构建器的 leftJoin()方法,因为在SQL查询中,您正在执行LEFT JOIN,例如:

$accounts= DB::table('parent_accounts as p')
               ->leftJoin('child_accounts as c','p.account_id','=','c.parent_id')
               ->select('p.name AS parent','c.name as name','c.account_id as account_id','c.parent_id as parent_id')
               ->get();

答案 1 :(得分:0)

如果您在使用Laravel数据库查询逻辑时遇到问题,可以执行原始sql requests或使用更简单的版本,例如this
例如:

$accounts= \DB::select(\DB::raw("
           SELECT * from parent_accounts
           LEFT JOIN child_accounts on 
           parent_accounts.account_id=child_accounts.parent_id");

但是如果你真的想了解你的问题在哪里,我建议你将你的数据库查询转换为sql并查看你的请求是否相同。更多here
TLDR;
只需在查询末尾添加->toSql()并阅读输出。将您的laravel查询转换为与它的SQL版本相同。

相关问题