简体   繁体   中英

Equivalent Laravel Eloquent for raw SQL query

I have recently started learning about php and laravel framework. Currently i am learning the Eloquent queries to store and retrieve data from the database. I am able to perform simple select, insert etc. queries however i am trying to understand more complex statement including joins.

This is the query i want to translate for example: $sql = "SELECT p.id , p.name" from clients c INNER JOIN partners p ON c.id = p.p_id where p.id = :param";

This works fine and gives the output, however the converted Eloquent does not provide the same output. What would be the correct conversion of this raw SQL query to Laravel Eloquent?. Also a little insight about joins in Eloquent would also be appreciated.

This is what i have tried:

DB::table('clients as c')
     ->join('partners as p', 'c.id', '=', 'p.c_id')
     ->where('p.id', '=', ':param')
     ->select('p.id' , 'p.name')
     ->get();

the parameter at the end is a variable you pass to you query builder ...

and for join , it's very simple and understandable

DB::table('clients as c')
     ->join('partners as p', 'c.id', '=', 'p.c_id')
     ->where('p.id', '=', $paramerterVariable)
     ->select('p.id' , 'p.name')
     ->get();
Client::join('partners as p', 'clients.id', '=', 'p.p_id')->where('p.id',  $paramerterVariable)
->where('client_id', $clientId)
            ->select('p.id' , 'p.name')
            ->get();

p.p_id it should be client_id in partners table

this is Laravel Eloquent for raw SQL query, or you can also use laravel relations with lazy loading and eager loading

$client = Client::where('id', $clientId);
$partners = $client->partners();

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