2017-04-24 16:41
浏览 441

Laravel Eloquent - 在find()方法中使用数组

I have three tables - users, products and orders There is a relation between users and orders (users has many orders).

orders table contains product_id and user_id column.

Now I want to access the product details of orders for a user.

What I am trying:

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

But this is not working. Can anyone help me? What other way can be better to achieve this?

图片转代码服务由CSDN问答提供 功能建议

我有三个表 - users products 和< 代码>订单 用户 orders 之间存在关系(用户有很多 orders ) 。

orders 表包含 product_id user_id 列。 < p>现在我想访问用户订单的产品详细信息。


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

但这不起作用。 谁能帮我? 还有什么方法可以更好地实现这一目标?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtiao1817 2017-04-24 16:45

    As mentioned, find() will always return 1 item, and expects a string/int for the parameter. You want to use where and get instead. With an array of ids, you can use whereIn.

    public function myOrders(){
        $orders = Auth::user()->orders->pluck('product_id');
        $products = Product::whereIn('id', $orders)->get();
        return view('shop.myorders', compact('products'));
    解决 无用
    打赏 举报
  • 查看更多回答(1条)

相关推荐 更多相似问题