鉴于通过Laravel Eloquent从DB获取成功并将更深层次的相关对象作为属性获取 - 如何按子对象属性深度排序?
答案 0 :(得分:2)
您可以将sortBy
方法与访问者属性一起使用:
class User extends Model
{
public function getNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
$users = MyModel::all()->sortBy('name');
答案 1 :(得分:1)
$stuff = MyModel::all();
$sortedStuff = $stuff->sort(function($a, $b)
{
$a = $a->getMyCalculatedAttribute();
$b = $b->getMyCalculatedAttribute();
//here you can do more complex comparisons
//when dealing with sub-objects and child models
if ($a->property === $b->property) {
return 0;
}
return ($a->property > $b->property) ? 1 : -1;
});