( (Where and Where) OR (Where and Where) ) Laravel 5.2

别来无恙 提交于 2020-08-27 05:57:09

问题


I am trying to create ( (Where and Where) OR (Where and Where) ) And after a lot of searching I found this

    $sender = \App\User::where('username','=',$username)->firstOrFail();
    $receiver = Auth::user();
    $messages = \App\Message::Where(function($query)
                              {
                                  $query->where("sender",$sender->id)
                                        ->where("receiver",$receiver->id);
                              })
                              ->orWhere(function($query)
                              {
                                  $query->Where("sender",$receiver->id)
                                        ->Where("receiver",$sender->id);
                              })
                              ->get();

But it's showing me that the $sender and the $receiver variables are undefined , Any help please , I'm trying to show the messages of the both users, I thought also that I can get the first (where and where) alone and then get the second one then I'll merge them.


回答1:


To use $send and $receiver within a Closure do the following;

function ($query) use($sender, $receiver){

}

Allowing you to access the variables within the scope of that function.

So your solution becomes;

$messages = \App\Message::Where(function($query) use ($sender, $receiver)
                          {
                              $query->where("sender",$sender->id)
                                    ->where("receiver",$receiver->id);
                          })
                          ->orWhere(function($query) use ($sender, $receiver)
                          {
                              $query->Where("sender",$receiver->id)
                                    ->Where("receiver",$sender->id);
                          })
                          ->get();



回答2:


You need to pass the variables through with use:

$messages = \App\Message::Where(function($query) use ($sender, $receiver)
                          {
                              $query->where("sender",$sender->id)
                                    ->where("receiver",$receiver->id);
                          })
                          ->orWhere(function($query) use ($sender, $receiver)
                          {
                              $query->Where("sender",$receiver->id)
                                    ->Where("receiver",$sender->id);
                          })
                          ->get();


来源:https://stackoverflow.com/questions/39371276/where-and-where-or-where-and-where-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!