0

我有一个 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');
}

请帮助将其转换为雄辩的模型查询 在此先感谢。

4

2 回答 2

2

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

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

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

于 2021-05-05T14:40:12.153 回答
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();
于 2021-05-05T14:43:28.983 回答