需要将查询转换为 Eloquent Model laravel

时间:2021-05-05 14:16:36

标签: mysql laravel eloquent laravel-relations

我有一个 MySQL 查询,但我需要将其转换为 eloquent 模型 laravel 8。查询如下,

$query = "SELECT  group_id FROM `chat_histories` join chat_group on chat_group.id = chat_histories.group_id where chat_group.is_group = 1 and chat_histories.created_at BETWEEN '$startDate' and '$endDate' and chat_histories.deleted_at is null group by group_id";
$query = "select count(group_id) as total_chat_thread from ($query) total_chat";
DB::select($query);

到目前为止,我已经做到了,

ChatHistory::leftJoin('chat_group', 'chat_group.id', '=', 'chat_histories.group_id')
        ->selectRaw('count(*) as totals')
        ->where('chat_group.is_group', 1)
        ->whereBetween('chat_histories.created_at', [$startDate, $endDate])
        ->groupBy('chat_histories.group_id')
        ->count('totals');

但这会返回一个列表,但我需要该列表的计数。这意味着它显示了 22 行,我需要那 22 行作为回报。

我的模型 ChatHistory 与 ChatGroup 的关系

 public function chatGroup() {
    return $this->belongsTo(ChatGroup::class, 'group_id', 'id');
}

我的模型 ChatGroup 与 ChatHistory 的关系

public function chatHistory() {
    return $this->hasMany(ChatHistory::class,'group_id','id');
}

请帮忙将其转换为雄辩的模型查询 提前致谢。

2 个答案:

答案 0 :(得分:2)

如果您的模型组具有 history hasMany 关系。应该是这样的。

$groupCount = ChatGroup::whereHas('chatHistory', function ($historyQB) use($startDate,$endDate)  {
    $historyQB->whereBetween('created_at', [$startDate, $endDate])
        ->whereNull('deleted_at');
})->count();

如果模型 ChatHistory 已启用 softDelete,则不需要 whereNull

答案 1 :(得分:0)

也许你应该考虑使用模型,它会更容易/更干净

这样的东西应该可以工作

DB::table('chat_histories')->select('group_id')->join('chat_group', 'chat_group.id', 'chat_histories.group_id')->where('chat_groups.is_group', 1)->whereBetween('chat_histories.created_at', $startDate, $endDate)->whereNull('chat_histories.deleted_at')->groupBy('group_id')->count();
相关问题