【问题标题】:How exclude record from eloquent where no relationship in Laravel?如何从 Laravel 中没有关系的 eloquent 中排除记录?
【发布时间】:2021-11-09 08:28:54
【问题描述】:

我有两个表“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】:

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

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

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

在 Query sells 中表示 hasMany 关系名称

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2021-04-10
    • 2016-02-18
    相关资源
    最近更新 更多