我希望只获取那些已经在产品表中的分类集合。我的分类表中有300个项目。只有当一个类别与产品表相关联时,我才想获取该集合。$categories集合应该只包括大约10个类别,因为只有约10个产品具有不同的category_id。
也许我使用的查询构建器方法不正确,需要尝试其他方法?
虽然最终结果 $categories 能够得到我想要的结果,但在我的 Blade 模板中出现了“Trying to get property of non-object”错误。
$products = DB::table('products')->groupBy('category_id')->get();
foreach($products as $product){
$categories[] = DB::table('categories')->where('id', '=', $product->category_id)->first();
}
$categories = collect($categories)->all();
也许我使用的查询构建器方法不正确,需要尝试其他方法?
虽然最终结果 $categories 能够得到我想要的结果,但在我的 Blade 模板中出现了“Trying to get property of non-object”错误。