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

时间:2016-08-31 18:04:19

标签: php mysql laravel laravel-5 distinct

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'

1 个答案:

答案 0 :(得分:0)

尝试使用groupBy()

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