我希望通过传递来自其他表
的ids
数组来获取所有产品
我可以获取product_id
中的所有dd($main_categorie_ids);
但无法在其他查询中传递它并获取所需数据
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)
谢谢
答案 0 :(得分: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();
答案 1 :(得分:1)
使用pluck
方法只获取ID,如下所示:
$productIds = DB::table($warehouse_table->table_name)
->select('product_id')
->distinct()
->pluck('product_id')
->toArray();
$products = Product::whereIn('id', $productIds)->get();