【问题标题】:Laravel using eloquent Count with HavingLaravel 使用雄辩的 Count 和 Have
【发布时间】:2020-05-27 01:34:49
【问题描述】:

我有两个变量 $customers(保存所有行)和 $total 保存查询的总行数。

我通常会做如下查询:

$customers = Customers::select
(
    'customer.id', 
    'customer.name', 
    'customer.min_tolerance',
    DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers);

$total = $customers->count();

$customers = $customers->limit($request->limit)
    ->offset($request->offset)
    ->get();

这很好用。我得到了所有行的限制(通常每页 20 行)加上总行数。

我的问题是我在查询中添加了having 子句,所以现在看起来像这样:

$customers = Customers::select
(
    'customer.id', 
    'customer.name', 
    'customer.min_tolerance',
    DB::raw('(SELECT MAX(tolerance) FROM customers_tolerances WHERE customer_id = customer.id) AS tolerance')
)
->from('customers AS customer')
->whereIn('customer.id', $request->customers)
->havingRaw('tolerance >= customer.min_tolerance');

$count 因触发错误而停止工作:

未找到列:1054“有子句”中的“容差”列未知 select count(*) as aggregate from customers as customer having tolerance >= customer.min_tolerance)

那么我如何将counthaving 子句一起使用?

【问题讨论】:

  • 如果您已经从“客户”模型中进行选择,我认为您不需要 ->from('customers as customer')。另外,请检查此答案。 stackoverflow.com/questions/50081540/laravel-where-count-n
  • 你的having子句中必须有一个聚合函数。
  • having 是不必要的,因为聚合位于子查询中。只需将其更改为 whereRaw
  • @aynber 您无法使用 where 访问别名变量。
  • @Hardood 你的意思是SELECT COUNT(*) FROM (SELECT ...)。如果是这样,我的问题是,我已经尝试过,是查询速度很慢。

标签: php laravel


【解决方案1】:

已解决

在创建这篇文章之前,我尝试创建一个子查询,如下所示:

SELECT COUNT(*) FROM (SELECT ...)

但是查询的速度太慢了,所以我试着在这里寻找答案。缓慢是由于表中缺少索引。

通过添加ALTER TABLE customers_tolerances ADD INDEX(customer_id);,我现在能够快速检索总结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-04
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多