使用口才/原始Laravel查询的群组Concat [英] Group Concat that use Eloquent/Raw Laravel Query

查看:51
本文介绍了使用口才/原始Laravel查询的群组Concat的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以雄辩形式存储的对象结构

I have an Object structure that is store in Eloquent Form

{"item_id": "2",
"item_color": "Black",
"item_size": "L",
"item_Quantity": "5",},

{"item_id": "2",
"item_color": "Black",
"item_size": "M",
"item_Quantity": "5",},

{"item_id": "2",
"item_color": "Black",
"item_size": "S",
"item_Quantity": "5",},

{"item_id": "2",
"item_color": "White",
"item_size": "S",
"item_Quantity": "5",},

我要实现的是将具有相同item_id和item_color的所有item_quantity合并,并以这种形式显示在表格中.

What I'm trying to achieve is to combine up all item_quantity which has the same item_id and item_color and Display in Table form like this.

ItemID ItemColor    L-M-S     Total
2         Black     5-5-5      15
2         White         5      5

这是我当前的查询

$items = DB::table('item')
            ->select(DB::raw("item_id,item_color,GROUP_CONCAT(item_size SEPARATOR '-') as ItemSize,GROUP_CONCAT(item_Quantity SEPARATOR '-') as Quantity,sum(item_Quantity) as TOTAL"))
            ->groupBy('item_id','item_color')
            ->get();

这是我已经解决的第一个查询:

This is my first Query that is already solved:

使用Eloquent Data Laravel的显示表表单

推荐答案

$items = DB::table('item')
            ->select(DB::raw("item_id,item_color,GROUP_CONCAT(item_Quantity SEPARATOR '-') as `L-M-S`,sum(item_Quantity) as TOTAL"))
            ->groupBy('item_id','item_color')
            ->get();

我希望这是您所需要的,记住在列名中使用连字符时,必须将其用反引号引起来.

I hope this is what you need , point to remember when using hypen in column name you have to make it wrapped with backticks.

这篇关于使用口才/原始Laravel查询的群组Concat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆