php - 如何从 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);
解决方案
您可以使用内部联接创建查询,但在 laravel 风格中您必须这样做......
- 在库存模型中创建 hasMany 关系。
- 如下更改您的查询
$inventory = Inventory::withCount('sells')->where('inventory.client_id', $user->client_id)->orderBy('sells_count', 'desc')->paginate(100);
在 Query sells 中表示 hasMany 关系名称
推荐阅读
- html - 这可以使导航栏附加到顶部吗?
- bash - 如何比较文件中行的最后一个单词
- html - 如何链接到字体真棒安装的路径
- amazon-web-services - GraphQL 中的双重关系
- python-3.x - Keras 库或者我应该从 Scratch 中选择神经网络吗
- rust - config crate 可以将环境变量合并到分层配置文件的一个小节中吗?
- hosting - 共享服务器兼 VPS
- javascript - 尝试使用 setTimeout() 每 5 秒间隔一次 XMLHttpRequest() API 调用时出现问题
- excel - 自动添加行
- flutter - 颤振:在后台消息处理程序没有被调用