Laravel 5.1如何使用lists()方法对集合进行排序

问题描述 投票:3回答:2

我有两个问题/帮助解决这里:

  1. 如何减少这行代码$this->all()->lists('name', 'id')->all()中的冗余
  2. 如何使用orderBy方法调用mutator。

helper.php

if (! function_exists('withEmpty')) {

    function withEmpty($selectList, $emptyLabel = '')
    {
        return array('' => $emptyLabel) + $selectList;
    }
}

Agent.php(型号)

public function getNameAttribute($value){
    return $this->lname.', '.$this->fname.' '.$this->mname;
  }

public function listAgents($emptyLabel = '--Select Agent--'){

    return withEmpty($this->all()->lists('name', 'id')->all(), $emptyLabel);


  }
php laravel laravel-5.1
2个回答
4
投票

1.改变这个:

$this->all()->lists('name', 'id')->all()

至:

$this->all()->lists('name', id)

你不能这样做。使用带有闭包的sortBy()sortByDesc()集合方法:

->sortBy(function($i) {
    return $i->name;
});

1
投票

您可以使用plucksortBy方法然后应用闭包

$this->pluck('name', 'id')->sortBy(function($el) {
    return $el->name;
});
© www.soinside.com 2019 - 2024. All rights reserved.