您将在底部找到整个功能。我希望查询是这样的,但在laravel查询构建器中:
$sql = "SELECT * FROM chat WHERE (sender='$receiver' AND
receiver='$sender'AND status='sent') OR (sender='$sender' AND
receiver='$receiver'AND status='sent')";
此查询应该从聊天中检索消息,例如:sender = 3和receiver = 4,反之亦然。这两个人之间基本上聊天。
现在我在laravel中创建了这样的东西,它返回整个聊天表,它应该只检索给定发送者和接收者之间的聊天。我知道问题出在where和orWhere子句中。
public function reloadChat(Request $request)
{
$sender = $request["sender"] ;
$receiver = $request["receiverid"] ;
$chats = DB::table('chats')
-> where(['sender_id' => $sender , 'receiver_id' => $receiver , 'status' => "sent" ])
-> orWhere(['sender_id' => $receiver , 'receiver_id' => $sender , 'status' => "sent" ])
->get();
foreach ($chats as $result)
{
if($result->sender_id==$sender)
{
echo "<div class=msgsend>".$result->message."</div>";
}else{
echo "<div class=msgrec>".$result->message."</div>";
}
}
}
P.S。 - 绝对是laravel的新手
这是有效的。但是当我使用变量而不是3和4 id时,它就不会。 public function reloadChat(Request $request)
{
$sender = $request["sender"] ;
$receiver = $request["receiverid"] ;
var_dump($sender) ;
var_dump($receiver) ;
$chats = DB::table('chats')
-> where(function($query) {
$query->where('sender_id', "3")
->where('receiver_id', "4")
->where('status', "sent");
})
-> orWhere(function($query) {
$query->where('sender_id', "4")
->where('receiver_id', "3")
->where('status', "sent");
})->get();
}
答案 0 :(得分:0)
你可以试试这个:
$chats = \DB::table('chats')
-> where(function($query) {
$query->where('sender_id', $sender)
->where('receiver_id', $receiver)
->where('status', status)
})
-> orWhere(function($query) {
$query->where('sender_id', $receiver)
->where('receiver_id', $sender)
->where('status', status)
})->get();
我发布的代码模拟括号,因此它与原始查询的行为相同。如果它不起作用,我认为问题出在其他地方,您可能需要重新检查原始查询或参数。
答案 1 :(得分:0)
访问文件Advanced wheres
使用示例
$chats = DB::table('chats')->where(function($query)
{
$query->where(['sender_id' => $sender , 'receiver_id' => "1", 'status' => "sent" ]);
})->orWhere(function($query)
{
$query->where(['sender_id' => "2", 'receiver_id' => "1", 'status' => "sent" ])
})->toSql();
toSql(); = return创建不带参数的sql命令