2

我有 2 个收藏。车辆和景观。我想带回按观看次数排序的车辆列表。

我的车辆类

class Vehicle extends Moloquent {

    protected $dates = ['date_assigned'];

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

}

还有我的 View 课

class View extends Moloquent {

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

}

事后我可以使用 $vehicle->associated_views->count() 获得视图计数,但这不能让我在拉回每条记录之前对字段进行排序。这可能吗?

4

1 回答 1

0

使用withCount()

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

如果您想在不实际加载关系的情况下计算关系结果的数量,您可以使用该withCount方法,该方法将{relation}_count在您的结果模型上放置一列

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

于 2017-10-16T15:44:00.727 回答