alihoushyaripour's avatar

How to write leftjoin eloquent with multiple conditions?

Hi,

I want to write an eloquent with multiple conditions like this:

$sql = "select * from table1_name left join table2_name on ... and on ... and on ...";

How can I write !?

0 likes
6 replies
Snapey's avatar

You can use the DB facade and its Where and Join functions, or you can learn about Eloquent ORM (where you rarely use joins)

jlrdw's avatar

Study this:

$apps = DB::table('products')
            ->select('products.*')
            ->leftJoin('ratings', 'products.id', '=', 'ratings.rateable_id')
            ->addSelect(DB::raw('AVG(ratings.rating) as average_rating'))
            ->groupBy('products.id')
            ->orderBy('average_rating', 'desc')
            ->paginate(session('posts_per_page'));

Came from this post

https://laracasts.com/discuss/channels/eloquent/orderby-computed-related-attribute

The ORM has all of the QB's methods also if needed.

The ORM can't solve everything, at times a normal query is needed.

But why don't you study the docs and take some lessons.

1 like
staudenmeir's avatar

It's possible with a closure:

DB::table('table1_name')
    ->leftJoin(function($join) {
        $join->on('a', '=', 'b')
            ->on('c', '=', 'd')
            ->on('e', '=', 'f');
    })->get();
Tray2's avatar

Yes

DB:select('SELECT t1.*, t2.* FROM table1 t1, table2 t2 
            WHERE t1.column1 = t2.column1
                    AND t1.column2 = t2.column2');

I much prefer the older join syntax then the newer one.

1 like
staudenmeir's avatar

Please replace ->get() with ->toSql() and post the result.

Please or to participate in this conversation.