我正在尝试对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']);
评论是我数据库中的一个数组
可以按数量订购吗?
答案 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']);