使用Eloquent进行回调的地方的关系过滤器

时间:2019-03-21 09:43:03

标签: laravel eloquent wherehas

给出以下模型

对话: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");
};

但是它不起作用。我该怎么办?

谢谢

1 个答案:

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