0

Is there a way to left join a raw statement in Laravel using Query Builder?

I have table A:

   a_id  |  name  |
-----------------
   1     |  Foo   |
   2     |  Bar   |

and table B:

   a_id  |  status  |
---------------------
   1     |   true   |
   2     |   false  |
   1     |   false  |
   2     |   true   |
   2     |   false  |

and table C:

   a_id  |  status  |
---------------------
   1     |   true   |
   2     |   true   |
   2     |   false  |

Then A left join B left join C should results:

   a_id  |  b_count  |   c_count
---------------------------------
   1     |     2     |     1
   2     |     3     |     2

I know doing such thing is so simple in pure SQL statement, but I have to do it with Query Builder.

1 Answer 1

1

I found it myself:

Model::selectRaw('
    A.a_id, 
    count(DISTINCT B.a_id) AS b_count, 
    count(DISTINCT C.a_id) AS c_count
')
    ->leftjoin('B', 'B.a_id', '=', 'A.a_id')
    ->leftjoin('C', 'C.a_id', '=', 'A.a_id')
    ->groupby('A.a_id');

Using DISTINCT was the key point in this case of joining more than two tables.

Sign up to request clarification or add additional context in comments.

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.