简体   繁体   中英

Laravel Select Row with Unique column

I have one database as follow:

id, shop, order_number, Price
1,  google, 11, 20
2,  apple, 12, 20
3, google, 13, 20
4, google, 11, 20,
5, google, 11 , 20

If I use the follow command in laraval:

Order::where('shop','=','google')->orderBy('id','desc')->get()->toArray();

It will perfectly show me results where shop is google.

however, i want to return only unique results by order_number and where shop is google. It should return following result:

1,  google, 11, 20
3, google, 13, 20

I try to use the following method:

Order::distinct()->where('shop','=','google')->orderBy('id','desc')->get(['id,shop,order_number,price'])->toArray();

But it seems not working.

Your syntax wrong: QueryBuilder get() expects an array of columns, so it should be like this:

Order::distinct()->where('shop','=','google')->orderBy('id','desc')->get(['id','shop','order_number','price'])->toArray();

Try this query:

Order::distinct()
->select('id','shop','order_number','price') //if you are selecting all column no need to write select
->where('shop','=','google')
->orderBy('id','desc')
->groupBy('order_number')
->get()
->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM