我有一个角色模型,其中包含一些访问器,该访问器计算与该模型有关的某些项目。我不能使用orderby,因为列不存在于db中,也不能使用sortby,因为我们使用了数据表(带有角度)。在postgres中,可以使用横向连接,但是正在使用mysql。还有其他方法吗?附件。
protected $appends = [
"changes_count"
];
public function getChangesCountAttribute()
{
return $this->changes()->where('type', 'Change')->count();
}
public function indexWithPagination(Request $request)
{
//Sorting
$column = isset($request->sortField) ? $request->sortField : null;
$order_by = 'asc';
if (isset($request->sortOrder)) {
$order_by = $request->sortOrder === 1 ? 'asc' : 'desc';
}
$record = Character::with(Character::getRelationshipsArray());
switch ($column) {
case 'cast':
$record->orderBy('character_number', $order_by);
break;
case 'changes_count':
??
break;
default:
$record->orderBy($column, $order_by);
break;
}
return getIndexWithPagination($record);
}
您可以按访问者对结果集合进行排序,显然,该查询无法排序,因为它不在数据库中。
$songs = Song::all(); // get the result
$songs->sortByDesc('lastDate'); // sort using collection method
// or ascending:
$songs->sortBy('lastDate');
如果您更愿意在数据库调用中使用连接,则可以实现相同的连接(在性能方面更好)。