【发布时间】:2021-07-27 21:11:39
【问题描述】:
我有一个MySQL的查询,但我需要将它转换成一个雄辩的模型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');
}
请帮忙把它转换成一个雄辩的模型查询 提前致谢。
【问题讨论】:
-
首先添加模型代码,声明关系
-
请检查问题,我已经编辑了我的问题并添加了我到目前为止所做的事情。
-
你有没有得到它与下面的答案一起工作?
标签: mysql laravel eloquent laravel-relations