0

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

enter image description here

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 ?

3
  • First things first, you are really not using laravel eloquent for join. You are using query builder. There is a difference between both. Try to define models properly and then use laravel eloquent. It will reduce joins to only one line. Commented Oct 19, 2017 at 13:21
  • @JunaidAhmad edit post Commented Oct 19, 2017 at 13:24
  • again bro dont use query builder untill or unless it's impossible with eloquents. Commented Oct 19, 2017 at 13:41

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.