afoysal's avatar

Multiple condition Laravel join()

How to add multiple condition in Laravel join() ? like

Post::has('comments.votes')->join('tafsir_ahbayan', 'tafsir_ahbayan.surah_id', '=', 'quran.surah_id'  // I would like to add more conditions here)->get();
0 likes
6 replies
AlexDemin's avatar
Post::has('comments.votes')
    ->join('tafsir_ahbayan', 'tafsir_ahbayan.surah_id', '=', 'quran.surah_id')
    ->where(...another conditions...)
    ->get();
AlexDemin's avatar

There are also Advanced Join Clauses:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

or

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();
1 like
afoysal's avatar

Thanks @AlexDemin . Can I use like below ?

Post::has('comments.votes')
    ->join('tafsir_ahbayan', 'tafsir_ahbayan.surah_id', '=', 'quran.surah_id','tafsir_ahbayan.my_id', '=', 'quran.my_id')
    ->get();
AlexDemin's avatar

I'd recommend using advanced joins in this case:

Post::has('comments.votes')
    ->join('tafsir_ahbayan', function ($join) {
        $join->on('tafsir_ahbayan.surah_id', '=', 'quran.surah_id')
             ->orOn('tafsir_ahbayan.my_id', '=', 'quran.my_id');
    })->get();
4 likes

Please or to participate in this conversation.