phplaravelormeloquent

Order by relationship min max value Laravel Eloquent


I have Flights model and Terms model.

Term model has price column.

I want to sort the flights in order of their lowest term price.

In the fights model I have

public function terms()
{
    return $this->hasMany('App\Term');
}

public function termMinPrice()
{
    if($this->terms()->count() > 0){
        return $this->terms()->pluck('price')->min();
    } else{
        return 0;
    }
}

How do you order this?


Solution

  • Edit Answer Try this

    Flight::with('terms')->get()->sortByDesc('terms.price');