简体   繁体   中英

Laravel select 3 rows from the same table with different value for a specified column

In my database is stored a table called 'advertisement' with the following records:

id |   code      | position
 1 |   header1   | header
 2 |   header2   | header
 3 |   header3   | header
 4 |   footer1   | footer
 5 |   footer2   | footer
 6 |   banner1   | banner
 7 |   banner2   | banner

I need to pick only one record for each 'position'. For example an output could be:

 1 |   header1   | header
 5 |   footer2   | footer
 7 |   banner2   | banner

How can I achieve this?

Advertisement::where(...)->distinct()->get();

This didn't do the magic because it's giving me distinct values considering all the columns, not only 'position'

尝试使用groupBy()

Advertisement::groupBy('position')->get();

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