如何在Laravel中对一组雄辩的对象进行排序?

时间:2016-07-10 20:23:35

标签: laravel sorting eloquent

鉴于通过Laravel Eloquent从DB获取成功并将更深层次的相关对象作为属性获取 - 如何按子对象属性深度排序?

2 个答案:

答案 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;
});