Laravel计数> ñ [英] Laravel Where Count > N

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

问题描述

我的应用程序中有2个模型:

I have 2 models in my app:

1。 Customer.php

2。 Car.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计数&gt; ñ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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