简体   繁体   中英

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

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

Result

在此处输入图片说明

When using laravel Query Builderas follows

 $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 ?

try to use the method leftJoin() of query builder, because in your SQL query you are doing a LEFT JOIN, for example:

$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
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. More here .
TLDR;
Simply add ->toSql() at the end of your query and read the output. Than transform your laravel query to be the same as it's SQL version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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