简体   繁体   中英

Laravel 5: Native SQL to Query Builder

I am trying to join 2 tables on Laravel 5 and have to use Query Builder. I have already got the sql for it but i am not able to convert it to Query Builder syntax. SQL is below

SELECT v.id, r.full_name, b.full_name, s.full_name
FROM vehicles v
LEFT JOIN clients r ON v.representive_client_id = r.id
LEFT JOIN clients b ON v.buyer_client_id = b.id
LEFT JOIN clients s ON v.seller_client_id = s.id

and what i tried is

    $query_result = DB::table('vehicles')   
                    ->selectRaw($query)
                    ->leftJoin('clients', 'vehicles.representive_client_id', '=', 'clients.id')
                    ->leftJoin('clients', 'vehicles.buyer_client_id ', '=', 'clients.id')
                    ->leftJoin('clients', 'vehicles.seller_client_id ', '=', 'clients.id')
                    ->paginate(30);

The problem is i dont know how to use AS caluse for Query Builder as i need to retrive 3 different types of full_name columns from vehicles table.Anybody can help me about how to write it in a proper Query Builder syntax ?. Any help would be appreciated.

You can use aliases with select columns and tables as well as joins, because the Query Builder will know to quote them correctly. So you can do this without any problems:

$query_result = DB::table('vehicles v')   
                ->select('v.id', 'r.full_name as r_name', 'b.full_name as b_name', 's.full_name as s_name')
                ->leftJoin('clients r', 'vehicles.representive_client_id', '=', 'r.id')
                ->leftJoin('clients b', 'vehicles.buyer_client_id ', '=', 'b.id')
                ->leftJoin('clients s', 'vehicles.seller_client_id ', '=', 's.id')
                ->paginate(30);

Of course, you can use whatever aliases you want for the selected columns. Actually one of the examples in the Query Builder Selects Documentation uses aliases: email as user_email .


To check the SQL query generated by the Query Builder you can use the toSql method. So in your case instead of ->paginate(30) you can have ->toSql() , which will return a string with the SQL generated by the Query Builder, which you can compare to your raw query and see if it matches.

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