【问题标题】:How to sort by relation by latest created_at column where has many in Laravel如何按 Laravel 中有很多的最新 created_at 列按关系排序
【发布时间】:2021-11-09 07:59:15
【问题描述】:

我有两个表“inventory”和“sell_records”的关系。库存中的每个产品都有许多销售记录。 我需要按最新销售记录订购所有产品。所以,我需要从产品的所有销售记录中找出该产品的最新销售记录,然后对所有产品进行排序。

这是我想出的脚本,但它仍然没有按应有的方式排序。

$inventory = Inventory::where('inventory.client_id', $user->client_id)
                                        ->join('inventory_sell_records', 'inventory_sell_records.product_id', '=', 'inventory.id')
                                        ->groupBy('inventory_sell_records.product_id')
                                        ->orderByRaw("max(inventory_sell_records.created_at) $order_by")
                                        ->paginate(100);

【问题讨论】:

    标签: php mysql laravel eloquent relational-database


    【解决方案1】:

    尝试使用:

    $inventory = Inventory::where('inventory.client_id', $user->client_id)
      ->join('inventory_sell_records', 'inventory_sell_records.product_id', '=', 'inventory.id')
      ->groupBy('inventory_sell_records.product_id')
      ->orderBy("inventory_sell_records.created_at", "desc")
      ->paginate(100);
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 2015-09-18
    • 2021-03-18
    • 2019-05-14
    • 2014-06-25
    • 2021-10-02
    • 1970-01-01
    • 2018-06-06
    • 2015-04-22
    相关资源
    最近更新 更多