首页 > 解决方案 > 如何从 Laravel 中没有关系的 eloquent 中排除记录?

问题描述

我有两个表“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);

标签: phpmysqllaraveleloquentrelational-database

解决方案


您可以使用内部联接创建查询,但在 laravel 风格中您必须这样做......

  1. 在库存模型中创建 hasMany 关系。
  2. 如下更改您的查询

$inventory = Inventory::withCount('sells')->where('inventory.client_id', $user->client_id)->orderBy('sells_count', 'desc')->paginate(100);

在 Query sells 中表示 hasMany 关系名称


推荐阅读