2017-01-17 43 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); 
}