Danabek Duisekov
Danabek Duisekov

Reputation: 325

How to use orderBy with count method

Corral model:

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

I want to order by number of sheep in each corral and get corral with fewest sheep number:

$corral = Corral::orderBy(..., 'ASC')->first();

Upvotes: 0

Views: 36

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14241

You could make use of withCount() and then order by this element I guess:

$corral = Corral
      ::withCount('sheeps')
      ->orderBy('sheeps_count', 'asc')
      ->first();

Check this section of the documentation.

Upvotes: 2

Related Questions