use distinct with multiple columns in laravel

痴心易碎 提交于 2020-12-30 08:55:01

问题


my table structure is as below

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

I need to fetch record like

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'

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


回答1:


Whenever we have multiple rows with same data that needs to be merged together in final output, we use group by functionality of mySQL.

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();

Explanation

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') It will merge the multiple records of same seller in same date.

->get(); we are get getting our data from the query.




回答2:


You could try

DB::table('orders')
    ->select('date', 'seller', DB::raw('SUM(total)'))
    ->groupBy('date')
    ->groupBy('seller')
    ->get();



回答3:


You should use advance search query. Here, this might help you




回答4:


$search = $request->search;

    $productSearch = Product::where('title', 'LIKE', '%'.$search.'%')
                    ->orWhere('description', 'LIKE', '%'.$search.'%')
                    ->get();

       return $produtcSearch;


来源:https://stackoverflow.com/questions/44382353/use-distinct-with-multiple-columns-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!