MySQL – SQL Join with Laravel Query Builder

MySQL

I have a transactions table with the following field:

Transactions
ID | amount | branch_id | supplier_id 
1  | 1,200  |    2      |  1

Subsidiary
ID  | Name      | Type
1   | supplier1 | 0
2   | branch_2  | 1

I want to display this in my view with the id value properly so I joined the following table (I'm using laravel query builder)

$transactions = DB::table('transactions_table')
->leftJoin('subsidiary_table','transactions_table.supplier_id','=','subsidiary_table.id')
->get(array('transactions_table.id',
'transactions_table.amount',
'subsidiary_table.name as branch',
'subsidiary_table.name as supplier'));

I'm confused on how can I get it to display like:

Display View
ID  |   Ammount  |  Supplier  | Branch 
1   |   1,200    |  Supplier1 | branch_2

Thanks for clarifying..

Best Answer

I don't know if you want to put it in laravel, but, here's the query:

SELECT
 t.ID,
 t.amount,
 s.Name as Supplier,
 sb.Name as Branch
FROM Transactions as t
JOIN Subsidiary as s ON (s.ID=t.supplier_id)
JOIN Subsidiary as sb ON (sb.ID=t.branch_id)
WHERE t.ID = 1;

Try it.

PD: You can change the JOIN syntax for LEFT JOIN if you want to return the t.ID = 1 record from Transactions even if one column don't match in Subsidiary's JOINs.