Laravel 从集合中获取产品 ID

Laravel get product id from collection

我想通过传递来自其他 table

ids 数组来获取所有产品

我能够获取 dd($main_categorie_ids); 中的所有 product_id 但无法在其他查询中传递它并获取所需的数据

    public function getHomeData($warehouse_id)
    {
        //get warehouse_table_name by warehouse_id
        $warehouse_table = Warehouse::where('id', $warehouse_id)
                                    ->select('table_name')
                                    ->first();

        //get all products from warehouse_table_name table
        $main_categorie_ids = DB::table($warehouse_table->table_name)
                                ->select('product_id')
                                ->get()
                                ->toArray();

        dd($main_categorie_ids);

        //dd result
        array:2 [
          0 => {#210
            +"product_id": 1
          }
          1 => {#209
            +"product_id": 2
          }
        ]

        //get distinct main_categories by id (line 29)
        $main_categorie = Product::whereIn('id', $main_categorie_ids['product_id'])
                                 ->groupBy('main_category_id')
                                 ->get();

        //get banners of main_categories by id 

        //get parent_categories by main_category_id 
    }

我遇到错误

(1/1) ErrorException
Undefined index: product_id
in HomeController.php (line 29)

谢谢

您的集合中有 1 个以上的数组,因此要使用特定的数组,您需要传递索引 所以试试这个

$main_categorie = Product::whereIn('id', $main_categorie_ids[0]->product_id)->get();

第一个,如果你想访问第二个

$main_categorie = Product::whereIn('id', $main_categorie_ids[1]->product_id)->get();

使用pluck方法只获取ids,像这样:

$productIds = DB::table($warehouse_table->table_name)
                            ->select('product_id')
                            ->distinct()
                            ->pluck('product_id')
                            ->toArray();
$products = Product::whereIn('id', $productIds)->get();