gpt4 book ai didi

php - 使用 laravel 查询构建器构建查询

转载 作者:行者123 更新时间:2023-11-29 03:18:59 27 4
gpt4 key购买 nike

您会在底部找到完整的功能。我希望查询是这样的,但是在 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>";
}

}

}

附言- 绝对是 laravel 的新手

编辑: this happens only when i pass the sender and receiver id's actual value in numbers(hard code) in where clause

这行得通。但是当我使用变量而不是 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();

}

最佳答案

访问文档 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(); = 返回创建的不带参数的sql命令

关于php - 使用 laravel 查询构建器构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424466/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com