【问题标题】:Laravel database ordering issue when using joins and order by使用连接和排序时的 Laravel 数据库排序问题
【发布时间】:2019-02-16 04:06:36
【问题描述】:

我有一个正在处理的项目,我有一个 StaffCustomerSale 模型。

正如预期的那样,Staff 可以有很多 Sales,其中有一个 Customer - Customer 也可以有很多 Sales。

在我正在处理的视图中,我想显示属于Staff 成员的所有Customers,但每个Customer 只显示一次(DISTINCT,GROUP BY?)但按最多的顺序显示最近的Sale (sale_date , DESC)。

我尝试了许多不同的方法来显示这个,但目前有这个代码:

Customer::join('sales', 'customers.id', '=', 'sales.customer_id')
->where('sales.staff_id',$id)
->orderBy('sales.sale_date', 'DESC')
->select('customers.*')
->get();

这在大多数情况下都有效,除了奇怪的记录,即八月中旬将有九月的记录。以下是我尝试过的其他一些方法:

$staff->sales()->orderBy('sale_date','DESC')->distinct('customer_id')->get();

Sale::select(DB::raw('s.*'))
->from(DB::raw('(SELECT * FROM sales WHERE staff_id = '.$id.' ORDER BY sale_date DESC) s'))
->groupBy('s.customer_id')
->orderBy('sale_date','DESC')
->get();

我不特别介意返回Sales 的集合,因为我可以修改我的视图以获取每个SaleCustomer

任何帮助/建议将不胜感激!

编辑:刚刚也注意到,甚至不再有不同的客户:(

【问题讨论】:

  • 如果将Sale::select 替换为DB::table('sales') 会发生什么?

标签: mysql laravel eloquent mariadb


【解决方案1】:

使用修改后的withCount() 通过子查询获取最新销售:

 Customer::withCount(['sales as sale_date' => function($query) {
        $query->select(DB::raw('max(sale_date)'));
    }])
    ->where('sales.staff_id', $id)
    ->orderByDesc('sale_date')
    ->get();

【讨论】:

  • 这样我得到以下错误:语法错误或访问冲突:1055 'db.customers.business_name' is not in GROUP BY (SQL: select customers.* from customers inner加入sales on customers.id = sales.customer_id 其中sales.staff_id = 1 组由customers.id 最大订购(sales.sale_date)desc) /跨度>
  • 你的 MySQL 版本是多少?
  • 10.3.9 - MariaDB
  • 建议的解决方案仅适用于 MySQL。我更新了我的答案。
  • 最后我一直在努力使任何事情都正常工作,因此通过获取所有客户、删除重复的键条目、然后对集合进行排序、最后颠倒顺序来解决冗长的解决方案。非常感谢您的帮助!
【解决方案2】:

根据joins documentation,连接功能直接使用数据库而不是模型,因此请尝试将Sale::select 替换为DB::table('sales')

【讨论】:

  • 有什么方法可以在保留模型实例的同时使用此方法吗?在视图中,我调用对视图至关重要的模型方法。就目前而言,使用此方法时,它会返回一个 stdClass 对象数组。
  • 在这种情况下,您需要使用Sales 模型并为每个Sale 获取客户。请记住预先加载客户模型以减少查询次数。
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多