Convert SQL query to Query Builder (Orange)

Asked

Viewed 609 times

0

I would like to convert the following query SQL to Query Builder (Laravel):

$duels = DB::select('SELECT r.id, r.name FROM tournaments t
            INNER JOIN duels d ON t.id = d.tournament_id
            INNER JOIN riders r ON d.rider_a_id = r.id OR d.rider_b_id = r.id
            WHERE t.id ='.$id)

Could someone help me?

Thanks in advance.

1 answer

0

I did the conversion, a tip is sometimes not to mount a query this way, because I took complex querys with more than 10 query lines that would become more than 30 and would be bad maintenance, but this is just a personal tip.

Follow the converted query:

$duels = DB::table('tournaments t')
            ->select('r.id', 'r.name')
            ->join('duels d', 't.id', '=', 'd.tournament_id')
            ->join('riders r', function($join){
                $join->on('d.rider_a_id','=','r.id'); 
                $join->orOn('d.rider_b_id','=','r.id');
            })
            ->where('t.id', '=', $id)
            ->get();

Result that she returned to me using the toSql();:

select `r`.`id`, `r`.`name` from `tournaments t` inner join `duels d` on `t`.`id` = `d`.`tournament_id` inner join `riders r` on `d`.`rider_a_id` = `r`.`id` or `d`.`rider_b_id` = `r`.`id` where `t`.`id` = ?

Test there and give a feedback, as I had no way to test, for more information I will leave the link documentation:

https://laravel.com/docs/5.7/queries

Browser other questions tagged

You are not signed in. Login or sign up in order to post.