【问题标题】:Laravel get product id from collectionLaravel 从集合中获取产品 ID
【发布时间】:2017-12-09 01:22:05
【问题描述】:

我想通过传递来自其他表的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)

谢谢

【问题讨论】:

    标签: php sql laravel laravel-5.4 laravel-query-builder


    【解决方案1】:

    您的集合中有超过 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();
    

    【讨论】:

    • 感谢您的宝贵时间,我确实尝试过,但我得到了不同的错误Cannot use object of type stdClass as array
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多