Laravel - 组基于相似的ID在Laravel
问题描述:
记录如何组基于相似的ID在Laravel 例如表中的记录: 在MySQL产品表有类似猫ID 表名folllowing记录:产品Laravel - 组基于相似的ID在Laravel
id:1 pro_name:xyz1 cat_id:55
id:2 pro_name:xyz2 cat_id:22
id:3 pro_name:xyz3 cat_id:55
id:4 pro_name:xyz4 cat_id:22
我想要做的是类似的cat_id它应该使其数组。我尝试使用
$all = Products::groupBy('cat_id')->get();
但它只显示每个类似cat_id的第一条记录。
输出我得到:
{
"id": 1,
"pro_name": "xyz1",
"cat": "55",
"created_at": "2017-02-09 13:09:13",
"updated_at": "2017-02-18 11:56:04"
},
{
"id": 2,
"pro_name": "xyz2",
"cat": "22",
"created_at": "2017-02-22 06:04:23",
"updated_at": "2017-02-22 06:04:23"
}
我想它应该显示类似ID的所有记录在一个阵列 帮我这个
答
集团通过总结你的表,使用给定的参数(因此它只显示第一个参数,而在奈尼的答案中,总计是为分组元素计算的)。
也许您在寻找Order By?
$info = DB::table('Products')
->orderBy('cat_id')
->get();
你会得到整个表,由cat_id
排序的结果,也就有了在一个类别手动变化来检测。
另一种方法是获取不同的cat_id,然后在它们上运行自己的查询。您可以将代码封装在模型或存储库中。请注意,这将在您的数据库上运行一些查询,这可能不是更可取的。
//Create an array
$groups = []
//Retrieve the list of cat_id's in use.
$cats = DB::table('Products')->distinct()->select('cat_id')->get()
//for each cat_id in use, find the products associated and then add a collection of those products to the relevant array element
foreach($cats as $cat){
$groups[$cat->cat_id] = DB::table('Products')->where('cat_id', $cat->cat_id)->get();
}
注意:我唯一关心的是你在这里做的是你真的在寻找关系吗?如果你使用Eloquent,所有这些变得非常简单。
答
可以试试这个
$info = DB::table('Products')
->select('cat_id', DB::raw('count(*) as total'),
DB::raw("GROUP_CONCAT(pro_name) AS product_name"))
->groupBy('cat_id')
->get();
答
嗨你应该试试这个代码...
$行=产品:: selectRaw( “pro_name,CAT_ID”) - > GROUPBY( “CAT_ID”, “pro_name”) - >获得();
echo "<pre>";
print_r($row);
你能分享所需的结果吗? – DevOps
可以使用GROUP_CONCAT,但要获取相同的数组,您需要运行单独的查询。 – DevOps