1

I want to fetch the data from database in laravel, which looks like this.

id | model_id | price
1 |1 | 200
2 |1 | 100
3 |2 | 500
4 |2 | 300
5 |2 | 400

I want the result as :

id | model_id | price
2 |1 | 200
4 |2 | 300

This is my code :

Model::modelfilter(Input::only('model_id', 'price'))->groupBy('model_id')->havingRaw('MIN(price)')->get();

Thank you.

Sunil tc
  • 2,482
  • 4
  • 19
  • 46

1 Answers1

2

Try this one,

$results = ModelName::select(['*',DB::raw('MIN(price) as min_price')])
              ->groupBy('model_id')
              ->get();

For Reference: https://laravel.com/docs/5.4/queries#raw-expressions

Balraj Allam
  • 611
  • 6
  • 24
  • I'm getting only min_price, I'm not getting other data. – Sunil tc Apr 13 '17 at 05:43
  • I got data like this, id | model_id | price 1 |1 | 200 3 |2 | 300 price is replacing for wrong data. I want like this, what can be done ? id | model_id | price 1 |1 | 200 4 |2 | 300 – Sunil tc Apr 13 '17 at 05:56
  • Did you replace `->groupBy('id')` with `->groupBy('model_id')`. I got it wrong there! – Balraj Allam Apr 13 '17 at 06:02
  • You need to join the same table again to get those results. Refer here http://stackoverflow.com/a/15292049/4584028 and https://laracasts.com/discuss/channels/laravel/join-same-table-with-two-columns. I think you cannot do it with the eloqount, you need to use the `DB::raw` – Balraj Allam Apr 13 '17 at 06:39