首页 > 解决方案 > 按大多数视图对结果进行排序

问题描述

我有来自“items”表的结果,它与“items_views”表相关联,它记录了每个视图。

我想按我的这段代码中的大多数视图对结果进行排序,我知道有一些简单的东西,但我找不到正确的语法,我也无法在文档中找到它。

$items = Items::whereHas('category', function ($query) {
    $query->where('status', 1); // only where the category it belongs to is active
})->whereHas('hot', function ($query) { // "hot" is the relationship with the "Items_views" model

    $query->orderBy('item_id_count', 'desc'); <-- EXAMPLE

})->whereHas('user', function ($query) {
    $query->where('access', 1); // only by users with a public profile
})->where('visible', 1)
    ->where('status', 1)
    ->orderByDesc('id')
    ->paginate(25);

编辑:

我的数据库表:

Items: id, user_id ecc
Items_views: id, item_id, user_id ecc

我的模型:

这是插入“Items.php”中的关系

public function hot(){
        return $this->belongsTo(ItemsViews::class);
    }

标签: laravel

解决方案


如果 item 和 item_views 表之间存在一对多关系,那么您需要将映射更正为

public function hot(){
    return $this->hasMany(ItemsViews::class);
}

然后您可以withCount在您的查询中使用并使用视图数对您的结果进行排序

$items = Items::withCount('hot')
    ->whereHas('category', function ($query) {
        $query->where('status', 1);
    })->whereHas('user', function ($query) {
        $query->where('access', 1);
    })->where('visible', 1)
      ->where('status', 1)
      ->orderByDesc('hot_count')
      ->paginate(25);

推荐阅读