php - Laravel HasManyThrough 带有 where 语句

标签 php laravel eloquent

我正在使用 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/

相关文章:

php - Doctrine MongoDb Embedded Document - 如何指定字段

php - 如何从CodeIgniter中的数据库中获取下拉列表中的数据

php - 如何在 Laravel 中的一条规则中验证整数和最大 float

php - Laravel 路由错误 404

mysql - 所需产品选项 laravel

php - 如何在 Laravel 4 中批量更新

laravel - Entrust - 获取角色所在的所有用户

php - 将HTML代码分为两个相等的内容部分,用PHP或JS

Laravel Eloquent 获取分组行的最新行

php - Windows Azure Blob 存储。 (点)在对象名称中被忽略