按相关(hasMany)文档的数量排序

Sort on the number of related (hasMany) documents

我有 2 个collections。 车辆和视图。 我想带回按观看次数排序的车辆列表。

我的车class

class Vehicle extends Moloquent {

    protected $dates = ['date_assigned'];

    public function associated_views()
    {
        return $this->hasMany('App\Collections\View');
    }

}

还有我的观点class

class View extends Moloquent {

    public function associated_vehicle()
    {
        return $this->belongsTo('App\Collections\Vehicle');
    }

}

我可以在事后使用 $vehicle->associated_views->count() 获取观看次数,但这并不能使我在撤回每条记录之前对字段进行排序.这可能吗?

使用withCount():

Vehicle::withCount('views')->latest('views_count')->get()

If you want to count the number of results from a relationship without actually loading them you may use the withCount method, which will place a {relation}_count column on your resulting models

https://laravel.com/docs/5.5/eloquent-relationships#counting-related-models