2017-04-24 150 views
0

陣列我有三個表 - usersproductsorders 有(users有很多ordersusersorders之間的關係。Laravel雄辯 - 使用find()方法

orders表中包含product_iduser_id列。

現在我想訪問用戶訂單的產品詳細信息。

我試圖:

public function myOrders(){ 
    $orders = Auth::user()->orders->pluck('product_id'); 
    $products = Product::find($orders); 
    return view('shop.myorders', compact('products')); 
} 

但是,這是行不通的。誰能幫我?有什麼其他方式可以更好地實現這一目標?

+0

查找相同as'where('id','=',?) - > first()'。改用' - > get()'和'whereIn()'。 – aynber

+0

是的,where()解決了我的問題。 –

回答

2

如上所述,find()將始終返回1項,並且期望參數的字符串/整數。您想要使用whereget。通過一系列ID,您可以使用whereIn

public function myOrders(){ 
    $orders = Auth::user()->orders->pluck('product_id'); 
    $products = Product::whereIn('id', $orders)->get(); 
    return view('shop.myorders', compact('products')); 
} 
+0

感謝您的解決方案。但laravel文檔說,我們可以使用數組作爲參數來調用find()方法來獲得匹配結果 - https://laravel.com/docs/5.4/eloquent#retrieving-single-models –

+0

啊,我看到他們添加了在5.2中。我必須記住這一點。 – aynber

1

我假設你已經orders()關係在Product模型中定義:

public function orders() 
{ 
    return $this->hasMany(Order::class) 
} 

然後你就可以加載的產品一切從用戶的訂單:

$products = Product::whereHas('orders', function($q) { 
     $q->where('user_id', auth()->id()) 
    })->get();