我需要对结果进行分页并使用sortBy()对其进行排序,而不会丢失分页链接。我还需要使用一种资源来返回结果。
$sorted = Model::paginate(10)->sortBy('name');
$results = \App\Http\Resources\MyResource::collection($sorted);
这样做会破坏分页链接(我只得到数据部分)。
$paginated = Model::paginate(10);
$results = \App\Http\Resources\MyResource::collection($paginated);
return $results->sortBy('name');
这也不起作用。有任何想法吗?
我已经通过以下解决方案解决了问题:
$sorted = Model::get()
->sortBy('example_function') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('model')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
我将example_function属性附加到模型中,以供sortBy使用。通过此解决方案,我能够使用orderBy对模型的附加属性进行排序。而且我也可以使用分页。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句