给出以下模型
对话:id,user_id,
消息:id,conversation_id,author_id,created_at
我想查询所有在$start
和$end
之间有消息的对话,所以我这样做了:
$filterMessages = function($query) use ($start, $end) {
$query->whereBetween("created_at", [$start, $end]);
};
$convs = Conversation::whereHas("messages", $filterMessages)
->with(["messages" => $filterMessages]);
它有效。现在,我需要添加一个条件:message.user_id必须与他对话的user_id相匹配(都在whereHas和with中)。所以我将回调更改为此:
$filterMessages = function($query) use ($start, $end) {
$query->whereBetween("created_at", [$start, $end]);
$query->where("conversations.user_id", "author_id");
};
但是它不起作用。我该怎么办?
谢谢
答案 0 :(得分:1)
尝试一下
Conversation Model
定义关系
public function userMessages()
{
return $this->hasMany(Message::class, 'author_id', 'user_id'); //your relationship based on data structure
}
$convs = Conversation::whereHas('userMessages',function($query) use ($start, $end) {
$query->whereBetween("created_at", [$start, $end]);
})
->with("userMessages")
->get();