Roberto Parma Roberto Parma - 3 months ago 15
MySQL Question

Laravel query builder grouping

i have a problem making laravel query:

I want for example:

SELECT * FROM USERS WHERE (a = b) or (b = a)


I have this but is not working:



$user = Auth::user();
$id_user = $user->id;
$message = DB::table('message')
->where('sender_id', '=', $user->id)
->where('reciver_id', '=', $id)
->orWhere(function($query) use ($id,$id_user){
$query-->where('sender_id', '=', $id)
->where('reciver_id', '=', $id_user);
})
->join('users', function ($join) {
$join->on('users.id', '=', 'message.sender_id')->orWhere('users.id', '=', 'message.reciver_id');
})->select('users.*', 'message.topic', 'message.message', 'message.read', 'message.created_at as date')
->orderBy('date')->get();

return $message;


Answer

You should nest the first two wheres in a new one. See the code below:

    $message = DB::table('message')
        ->where(function($query) use ($id,$id_user){
            $query->where('sender_id', '=', $id_user)
                ->where('reciver_id', '=', $id);
        })
        ->orWhere(function($query) use ($id,$id_user){
            $query->where('sender_id', '=', $id)
                ->where('reciver_id', '=', $id_user);
        })
        ->join('users', function ($join) {
            $join->on('users.id', '=', 'message.sender_id')->orWhere('users.id', '=', 'message.reciver_id');
        })->select('users.*', 'message.topic', 'message.message', 'message.read', 'message.created_at as date')
        ->orderBy('date')->get();