doulao2916 2017-04-24 16:41
浏览 536
已采纳

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?

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable