【问题标题】:Laravel Where Count > NLaravel 计数 > N
【发布时间】:2018-10-09 10:17:42
【问题描述】:

我的应用中有 2 个模型:

1.客户.php

2。汽车.php

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

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

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

编辑: 这两个模型链接在一个数据透视表中,这意味着一个客户可以拥有超过 1 辆汽车,而一辆汽车可以属于超过 1 个客户。

【问题讨论】:

    标签: laravel eloquent laravel-5.6


    【解决方案1】:

    使用这个:

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

    【讨论】:

    • 其实现在可以了,以前没用,因为我的关系没有正确设置。
    • 这只有在查询被分组时才有效,否则它会抛出unknown column cars_count
    • 你如何按查询分组?这个答案不完整,它不能按原样工作
    【解决方案2】:

    所以,结果如下。

    模型Customer.php中的关系

    public function cars()
    {
        return $this->belongsToMany('App\Car','car_customer','car_id','customer_id');
    }
    

    查询所有拥有 N 辆车的客户:

     $userInput = 2;
     $data = Customer::with('cars')
                    ->withCount('cars')
                    ->has('cars', '<', $userInput)
                    ->orderBy('cars_count', 'desc')
                    ->get();
    

    $userInput 是您的“N”。

    【讨论】:

    • 这行得通,但是 Jonas 的解决方案绝对更好,因为这个解决方案再执行 1 个子查询。
    • Jonas 的解决方案会说没有列 'cars_count'
    • 如果关系设置正确,则不会。如果不是,这也行不通。另外,如果没有cars_count 列,您为什么希望-&gt;orderBy('cars_count') 工作?至于解释,-&gt;withCount('cars') 在 select 中添加了一个cars_count。它创建一个计算关系的子查询。
    • 谢谢,这有效,@devk 是对的,Jonas 的回答最初对我不起作用,因为我的关系设置不正确,感谢您的帮助 o/
    • @user3718908 ,whereHas()has() 相同,但 whereHas() 允许指定相关模型上的附加过滤器,has() 根据关系过滤选择模型。
    【解决方案3】:

    你试过这种方法吗?

    $input = 2;
    $customers = Customer::whereHas("cars", function($query) use ($input) {
        $query->where(DB::raw("count(cars.id)"), "<", DB::raw($input))
    })->get();
    

    【讨论】:

    • 不,我没有,我忘了补充一点,客户和汽车是在数据透视表上连接的。
    • 请提供一个sqlfiddle
    • 这只是一个 belongsToMany 关系。这意味着我的数据库中有一个 customer_car 数据透视表。
    • 我知道。但我需要在原始 sql 中编写该查询,所以我可以在 laravel 中编写该查询。
    • 请为每个表添加一些 3-4 行。
    【解决方案4】:

    这是最好的方法:

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

    【讨论】:

    • 您好,欢迎您!请解释为什么这是您认为的最佳解决方案。
    • 因为它简单,一行代码,你不必加载任何关系或使用“有”查询。
    猜你喜欢
    • 2015-03-20
    • 2010-10-18
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    相关资源
    最近更新 更多