2017-01-17 40 views
2

我正在使用Laravel 5.3,我试图使用HasManyThrought关系与where声明,但我不知道如何实现该目标。Laravel HasManyThrough与哪里的说法

所以我有这些表:

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) 
} 

但是!如果我想取他们的订单记录为complete

回答

2

如果你想获得与complete国家认证用户的所有项目,使用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); 
}