使用雄辩的orm按laravel 5.5中的列数排序

时间:2019-01-09 17:10:44

标签: laravel

我正在尝试对larvel模型内部字段的计数设置by子句。
我在Eloquent上使用mongodb。
甚至有可能吗?

这是我要运行的查询的简短摘要:

$books = Books::where(function ($query) use ($params, $res) {
                    $query->where('labels', 'elemMatch', array(
              'genre' => $res->genre,
                            'outdated' => $res->false
                        ))
                        ->where('available', true)
                        ->where('isSelling', true);
                })
                    ->orderBy('reviews','desc')
                    ->paginate($params['limit']);

评论是我数据库中的一个数组
可以按数量订购吗?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样做

$books = Books::where(function ($query) use ($params, $res) {
                $query->where('labels', 'elemMatch', array(
          'genre' => $res->genre,
                        'outdated' => $res->false
                    ))
                    ->where('available', true)
                    ->where('isSelling', true);
            })
                ->orderBy('reviews','desc')
                ->get();

// sorting the books using sortBy or sortByDesc
$books = $books->sortByDesc(function($book){
              return count(json_decode($book->reviews)); // we return the count of the reviews here
          }

// get sorted ids of the books
$ids = $books->pluck('id')->toArray();

// we get the books paginated with the ids order 
$books = $books->whereIn('id',$ids)
               ->orderByRaw(\DB::raw("FIELD(id, $ids)"))
               ->paginate($params['limit']);