0
votes

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;

1
What exactly is not working?lesssugar
Can you elaborate on how your code "doesn't work"? What were you expecting, and what actually happened? If you got an exception/error, post the line it occurred on and the exception/error details. Please edit these details in or we may not be able to help.Goodbye StackExchange

1 Answers

1
votes

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();