2017-04-24 39 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();