在laravel中使用不重复的多列 [英] use distinct with multiple columns in laravel
问题描述
我的表结构如下
date seller unit price total
05-06-17 abc 14 700 9800
05-06-17 pqr 12 600 7200
05-06-17 abc 10 520 5200
06-06-17 abc 10 600 6000
06-06-17 pqr 15 520 7800
06-06-17 pqr 16 520 8320
我需要像这样获取记录
1) 'date' = '05-06-2017', 'seller' = 'abc', 'total' = '15000'
2) 'date' = '05-06-2017', 'seller' = 'pqr', 'total' = '7200'
3) 'date' = '06-06-2017', 'seller' = 'abc', 'total' = '6000'
4) 'date' = '06-06-2017', 'seller' = 'pqr', 'total' = '16120'
我需要按日期排列数据库中的数据.卖方
abc
在表中有两个条目用于 date
05-06-2017
,所以我需要 total当天
以及第二天卖方
abc
的 date
的所有 pqr
相同的内容,code>卖家
I need data from database in date wise. seller
abc
has two entry in a table for date
05-06-2017
so I need total
of that day for seller
abc
as well pqr
same things for the second date
for all seller
推荐答案
每当我们有多行具有相同数据的行需要在最终输出中合并在一起时,我们将使用 group by 功能> mySQL .
Whenever we have multiple rows with same data that needs to be merged together in final output, we use group by functionality of mySQL.
因此,在您的情况下,您可以使用laravel查询构建器以这种方式进行操作.
so in your case you can use laravel query builder to do it in this way.
DB::table('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
->groupBy('seller')
->groupBy('date')
->get();
说明
DB :: select('orders')->选择('date','seller',DB :: raw('SUM(total)as total')')
将查询我们数据库中的 orders
表&然后获取我们提供的列,即日期,卖方和总列的总和作为总金额
DB::select('orders')->select('date', 'seller', DB::raw('SUM(total) as total'))
will query our orders
table in our database & then fetch our provided columns i.e. date, seller and sum of total column as total
-> groupBy('seller')-> groupBy('date')
它将在同一日期合并同一卖方的多个记录.
->groupBy('seller')->groupBy('date')
It will merge the multiple records of same seller in same date.
-> get();
我们正在从查询中获取数据.
->get();
we are get getting our data from the query.
这篇关于在laravel中使用不重复的多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!