我只想在商品表中获取类别的集合.我的类别表有300个项目.如果在产品表中附加了类别,我只想要一个集合. $categories集合仅应产生约10个类别,因为只有约10个产品具有不同的category_id
$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确实得到了我想要的结果,但是在刀片中我得到了“试图获取非对象的属性”错误.
解决方法:
您会尝试获取非对象的属性,因为其中之一
DB::table('categories')->where('id', '=', $product->category_id)->first();
返回空值.
你可以这样解决
$products = DB::table('products')->groupBy('category_id')->get();
$categories = collect();
foreach($products as $product){
$category = DB::table('categories')->where('id', '=', $product->category_id)->first();
if ($category) {
$categories->push($category);
}
}
如果要获取集合实例,则必须使用带有数组参数的collect()帮助器方法.
例如
collect($categories); // is_array(categories) is true
您在foreach中有很多要求.那不是正确的方法.相反,您可以仅执行2个请求即可实现集合实例.
$categoryIds = DB::table('products')->pluck('category_id')->toArray();
$categories = DB::table('categories')->whereIn('id', $categoryIds)->get();
标签:laravel,php
来源: https://codeday.me/bug/20191108/2005253.html