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

3

我这里有两个问题需要解决:

  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);


  }
2个回答

4

1. 把这个改成:

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

致:

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

2. 你不能这样做。使用闭包和 sortBy() 以及sortByDesc()集合方法:

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

谢谢,但在“pluck”中,Laravel仍然抛出异常“Column not found: 1054 Champ 'name'”。 - jp.palubs
@jp.palubs 哦,你在使用5.1版本。在这种情况下,请使用我在更新的答案中展示的lists()函数。 - Alexey Mezenin
仍然存在错误,但当我将“name”更改为“lname”时,它可以正常工作(因为这是表中的字段名称)。但是当我尝试使用“name”突变剂时,它不起作用。我应该尝试通过其他方式调用“name”还是在我的代码中组合两个字段? - jp.palubs
@jp.palubs,由于name是一个访问器,所以请使用all()->lists('name', 'id')。对于列,您不需要先执行查询。因此,当您使用all()->listst()时,您正在使用集合方法而不是Eloquent构建器方法。 - Alexey Mezenin
现在它会抛出“试图获取非对象属性”的错误,这是因为我把代码放在了模型里吗? - jp.palubs
@jp.palubs 我认为这个错误不是与代码相关的。 - Alexey Mezenin

1
你可以使用 plucksortBy 方法,然后应用一个闭包。
$this->pluck('name', 'id')->sortBy(function($el) {
    return $el->name;
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接