Laravel中的MySQL查询
我有两张桌子:餐厅和点菜餐厅 “餐厅订单”表存储预订和订购项目的数据。 我试图显示(在图表中)特定项目的订购次数。因此乘以数量 控制器Laravel中的MySQL查询,mysql,laravel,Mysql,Laravel,我有两张桌子:餐厅和点菜餐厅 “餐厅订单”表存储预订和订购项目的数据。 我试图显示(在图表中)特定项目的订购次数。因此乘以数量 控制器 public function restaurant(){ $data = DB::table('restaurant_orders') ->join('restaurants', 'restaurant_id', '=', 'restaurants.id') ->select( DB::raw('item a
public function restaurant(){
$data = DB::table('restaurant_orders')
->join('restaurants', 'restaurant_id', '=', 'restaurants.id')
->select(
DB::raw('item as item'),
DB::raw('count(*) * quantity as total'))
->groupBy('item','quantity')
->get();
$array[]=['Item', 'Total'];
foreach($data as $key=>$value)
{
$array[++$key] = [$value->item, $value->total];
}
return view('executive.restaurant')->with('item',json_encode($array));
}
我得到的输出:
+-------------------+-------+
| Item | Total |
+-------------------+-------+
| Cake (slice) | 2 |
| Cake (slice) | 3 |
| Fried Rice | 1 |
| Hot & Sour Soup | 1 |
| Hummus | 2 |
| Soft Drinks | 2 |
| Vanilla milkshake | 1 |
+-------------------+-------+
我不想重复上面提到的“蛋糕(片)”中的相同项目。我希望它像:
+-------------------+-------+
| Item | Total |
+-------------------+-------+
| Cake (slice) | 5 |
| Fried Rice | 1 |
| Hot & Sour Soup | 1 |
| Hummus | 2 |
| Soft Drinks | 2 |
| Vanilla milkshake | 1 |
+-------------------+-------+
编辑:
将查询更改为
sum(1*quantity)as total
和(int)$value->total
解决了问题。这是由谷歌图表引起的。它给出了一个错误。SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,以了解在第1行的restaurant\u orders
internal joinrestaurants
中使用near')as total的正确语法(SQL:选择项作为项,sum()在我使用您的查询后,restaurant\u orders
internal joinrestaurant\u id
=restaurants
id
group byitem
)上的instaurants
内部连接restaurants
尝试将sum(*)更改为sum(1)
看看这是否有帮助。。。如果不是的话,我建议看一些关于如何在ORM Laravel使用中进行求和选择的教程……我尝试使用您的逻辑来解决这个问题,我以前也尝试过。我不希望它是sum()
对于项目,我希望每个项目都显示订购的次数。您的查询给出了在不包括要乘以的“数量”列的情况下订购的次数。还是谢谢你试着帮助我,我很感激。那么为什么不把这里的总和乘以数量的总和呢?如果你的意思是用项目的总和乘以数量的总和,那么它就不起作用了。也许你可以给我发个问题,问一下你想向我解释什么,这样我才能更好地理解?
+-------------------+-------+
| Item | Total |
+-------------------+-------+
| Cake (slice) | 5 |
| Fried Rice | 1 |
| Hot & Sour Soup | 1 |
| Hummus | 2 |
| Soft Drinks | 2 |
| Vanilla milkshake | 1 |
+-------------------+-------+
public function restaurant() {
$data = DB::table('restaurant_orders')
->join('restaurants', 'restaurant_id', '=', 'restaurants.id')
->select(
DB::raw('item as item'),
DB::raw('sum(1 * quantity) as total'))
->groupBy('item')
->get();
$array[]=['Item', 'Total'];
foreach($data as $key=>$value) {
$array[++$key] = [$value->item, (int) $value->total];
}
return view('executive.restaurant')->with('item', json_encode($array));
}