我正在使用 Laravel 5.3,并且尝试将 HasManyThrought
关系与 where
语句一起使用,但我不知道如何实现该目标。
所以我有这些表:
Users:
+----+-------+
| id | name |
+----+-------+
| 1 | James |
+----+-------+
Orders:
+----+---------+------------+
| id | user_id | state |
+----+---------+------------+
| 1 | 1 | complete |
+----+---------+------------+
| 2 | 1 | incomplete |
+----+---------+------------+
| 3 | 1 | pending |
+----+---------+------------+
Order Items:
+----+----------+--------+
| id | order_id | name |
+----+----------+--------+
| 1 | 1 | Mac |
+----+----------+--------+
| 2 | 1 | Tablet |
+----+----------+--------+
| 3 | 2 | Laptop |
+----+----------+--------+
现在我想获取用户的订单商品,所以我会这样做:
public function items()
{
$this-hasManyThrough(Item::class, Order::class)
}
但是!如果我想仅获取其订单被声明为完整
的商品,该怎么办?
最佳答案
如果您想获取已验证用户的所有处于完整
状态的项目,请使用whereHas()
方法:
$items = Item::whereHas('order', function($q) {
$q->where('state', 'complete')
->where('user_id', auth()->user()->id);
})->get();
不要忘记在 Item
模型中定义 order()
关系:
public function order()
{
return $this->belongsTo(Order::class);
}
关于php - Laravel HasManyThrough 带有 where 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41697893/