laravel eloquent 列表 - 对列值列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17608160/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:33:18  来源:igfitidea点击:

laravel eloquent lists - Sorting A List Of Column Values

laraveleloquent

提问by Ray

Using laravel and I'm creating a select box on a form. I've been using the helper to create the select box and all is working fine.

使用 laravel,我在表单上创建了一个选择框。我一直在使用助手来创建选择框,一切正常。

I retrieve the data for the select box from a database and use the following to retrieve the data:

我从数据库中检索选择框的数据并使用以下方法检索数据:

$data = model::lists('name','id')

Again all works ok and this returns the expected array

再次一切正常,这将返回预期的数组

My problem though is I can't seem to sort this list - i've tried adding orderBy() but no joy.

我的问题是我似乎无法对这个列表进行排序 - 我已经尝试添加 orderBy() 但没有任何乐趣。

Other than using a native php function is there a laravel method to sort a list?

除了使用本机 php 函数之外,还有一种 Laravel 方法可以对列表进行排序吗?

回答by Umut Sirin

You can put whatever you want, and then list it. I mean:

你可以放任何你想要的,然后列出来。我的意思是:

model::orderBy('orderByColumn')->lists('name', 'id');

As long as listsis the last method in the chain, other methods works just fine.

只要lists是链中的最后一个方法,其他方法就可以正常工作。



Starting from Laravel version 5.3listsis going to be deprecated, use pluckinstead:

从 Laravel 5.3 版lists开始将被弃用,请pluck改用:

model::orderBy('orderByColumn')->pluck('name', 'id');

回答by thestepafter

You can try:

你可以试试:

$data = model::select('name','id')->orderBy('name');

If that doesn't work, toss a ->get()on the end:

如果这不起作用,请->get()在最后抛出一个:

$data = model::select('name','id')->orderBy('name')->get();

回答by V? Ng?c Nh?t

when I

当我

dd(YourModel::pluck('name', 'id'));

I see it is Collection Class so I found collection laravel and then I found method sortKeys() so I do:

我看到它是 Collection Class 所以我找到了 collection laravel 然后我找到了 sortKeys() 方法所以我这样做:

YourModel::pluck('name', 'id')->sortKeys();