如何将 orderBy 与 count 方法一起使用

How to use orderBy with count method

畜栏模型:

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

我想按每个畜栏中羊的数量排序,得到羊数量最少的畜栏:

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

您可以使用 withCount() 然后按我猜的这个元素排序:

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

检查文档的 this section