Laravel Where Count >N [英] Laravel Where Count > N

查看:21
本文介绍了Laravel Where Count >N的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有 2 个模型:

I have 2 models in my app:

1.客户.php

2.汽车.php

现在我想运行一个查询,返回所有拥有少于 2 辆车的客户.其中 2 是用户可以更改的数字.

Now I would like to run a query that returns all customers that have less than 2 cars. Where 2 is a number that can be changed by the user.

我试过了,但没有用,它只是返回所有客户记录:

I have tried this but it didn't work, it just returns all customer records:

$customers = Customer::whereHas("cars", function($query) {
    $query->selectRaw("count(*) < ?", [2]);
})
->get();

这两个模型在数据透视表中链接,这意味着一个客户可以拥有 1 辆以上的汽车,而一辆汽车可以属于 1 个以上的客户.

The two models are linked in a pivot table, meaning A customer can have more than 1 car and a Car can belong to more than 1 customer.

推荐答案

使用这个:

$customers = Customer::withCount('cars')
    ->having('cars_count', '<', 2)
    ->get();

这篇关于Laravel Where Count >N的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆