微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

需要将查询转换为 Eloquent Model laravel

如何解决需要将查询转换为 Eloquent Model laravel

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

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

解决方法

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

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

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

,

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

这样的东西应该可以工作

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。