简体   繁体   English

Laravel查询生成器联接与RAW不同

[英]Laravel Query Builder Join is diffrent from RAW

I'm using laravel Query Builder to join two table from mysql db When i use raw query in the shell 当我在外壳中使用原始查询时,我正在使用laravel查询生成器从mysql db连接两个表

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

Result 结果

在此处输入图片说明

When using laravel Query Builderas follows 当使用laravel查询生成器时如下

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

i never get the 4th row, isn't that result if i used left join with child_accounts first ? 我从不进入第4行,如果我先使用child_accounts左联接,那不是结果吗?

try to use the method leftJoin() of query builder, because in your SQL query you are doing a LEFT JOIN, for example: 尝试使用查询生成器的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();

If you have some problems with Laravel DB query logic you can perform raw sql requests or use simpler version like this 如果您对Laravel DB查询逻辑有疑问,可以执行原始sql 请求或使用像这样的简单版本
For example: 例如:

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

But if you really want to understand where is your problem, I'd recommend you to transform your DB query to sql and look if your requests are the same. 但是,如果您真的想了解问题出在哪里,我建议您将数据库查询转换为sql并查看您的请求是否相同。 More here . 这里更多。
TLDR; TLDR;
Simply add ->toSql() at the end of your query and read the output. 只需在查询末尾添加->toSql()并读取输出。 Than transform your laravel query to be the same as it's SQL version. 比将您的laravel查询转换为与SQL版本相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM