如何在 Laravel 中将 orderBy() 与模型的方法一起使用
How to use orderBy() with model's method in Laravel
如何使用 orderBy 通过模型的方法进行排序?
考虑模型用户和方法
public function fullName() {
return $this->firstName . $this->lastName;
}
我想做一些类似 orderBy('fullName') 的事情。这可能吗?我知道我可以使用 Query Builder 编写等效代码,但我想保持我的模型方法不变。
我想你在这里有几个选择:
- 在您的数据库中创建一个视图,其中包含列
fullName
。然后更改模型以使用视图。
- 创建一个计算列 fullName,以便在插入时使用 firstName 和 lastName 给定的值。
- 使用 Laravel 的 Collection class。 class 提供了一个可以使用属性的 sortBy 方法。
如果选择选项 2,首先定义一个属性:
public function getFullNameAttribute()
{
return $this->firstName . $this->lastName;
}
然后使用 Laravel 的 Collection:
$items = Model::all()->sortBy('FullName');
注意:sortBy
的默认选项是升序,所以如果你想降序排序:
$items = Model::all()->sortByDesc('FullName');
您可以在此处阅读有关访问器的更多信息:https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor
我已经用这个解决方案解决了这个问题:
$sorted = User::get()
->sortBy('full_name') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('user')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
我已将 fullName 属性附加到模型,以供 sortBy 使用。
通过这个解决方案,我能够使用 orderBy 按模型的附加属性进行排序,这正是我想要做的。所以是的,这是可能的。而且我还能够使用分页。感谢所有试图提供帮助的人。
$personas = Persona::select('*');
$personas = $personas->addSelect(DB::raw('concat(nombre,\' \',apellido1,\' \',apellido2) as fullname'))
->orderBy('fullname', 'ASC')->paginate(K_LINEAS_X_PAGINA);
没有 select('*')
我无法让它工作
如何使用 orderBy 通过模型的方法进行排序?
考虑模型用户和方法
public function fullName() {
return $this->firstName . $this->lastName;
}
我想做一些类似 orderBy('fullName') 的事情。这可能吗?我知道我可以使用 Query Builder 编写等效代码,但我想保持我的模型方法不变。
我想你在这里有几个选择:
- 在您的数据库中创建一个视图,其中包含列
fullName
。然后更改模型以使用视图。 - 创建一个计算列 fullName,以便在插入时使用 firstName 和 lastName 给定的值。
- 使用 Laravel 的 Collection class。 class 提供了一个可以使用属性的 sortBy 方法。
如果选择选项 2,首先定义一个属性:
public function getFullNameAttribute()
{
return $this->firstName . $this->lastName;
}
然后使用 Laravel 的 Collection:
$items = Model::all()->sortBy('FullName');
注意:sortBy
的默认选项是升序,所以如果你想降序排序:
$items = Model::all()->sortByDesc('FullName');
您可以在此处阅读有关访问器的更多信息:https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor
我已经用这个解决方案解决了这个问题:
$sorted = User::get()
->sortBy('full_name') //appended attribute
->pluck('id')
->toArray();
$orderedIds = implode(',', $sorted);
$result = DB::table('user')
->orderByRaw(\DB::raw("FIELD(id, ".$orderedIds." )"))
->paginate(10);
我已将 fullName 属性附加到模型,以供 sortBy 使用。 通过这个解决方案,我能够使用 orderBy 按模型的附加属性进行排序,这正是我想要做的。所以是的,这是可能的。而且我还能够使用分页。感谢所有试图提供帮助的人。
$personas = Persona::select('*');
$personas = $personas->addSelect(DB::raw('concat(nombre,\' \',apellido1,\' \',apellido2) as fullname'))
->orderBy('fullname', 'ASC')->paginate(K_LINEAS_X_PAGINA);
没有 select('*')
我无法让它工作