如何在 Laravel 中按字母顺序对记录进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47246772/
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-14 16:57:20  来源:igfitidea点击:

How to sort records in alphabetical order in Laravel

phplaravelblade

提问by K.Mihiranga

How to sort records in alphabetical order in laravel?

如何在laravel中按字母顺序对记录进行排序?

public function index()
{
    $comproducts = Comproduct::paginate(3);

    $items = Item::orderBy('name')->all();        

    return view('computer', compact(['comproducts', 'items']));

}

This is not working correctly. This shows

这不能正常工作。由此可见

Call to undefined method Illuminate\Database\Query\Builder::all()

调用未定义的方法 Illuminate\Database\Query\Builder::all()

this error. How can i fix this?

这个错误。我怎样才能解决这个问题?

回答by Niklesh Raut

I use get()instead , you can't modify query with method all()and also it is static function

get()改用,你不能用方法修改查询,all()而且它是静态函数

  $items = Item::orderBy('name')->get(); 

回答by Milan Chheda

That's how you sort it, orderBy()comes after all():

这就是你的排序方式,orderBy()后面是all()

$items = Item::all()->sortBy('name');    

Reference: https://laravel.com/docs/5.5/collections

参考:https: //laravel.com/docs/5.5/collections

回答by Krishnamoorthy Acharya

Hi Please find an answer based on eloquent query laravel

嗨,请根据 eloquent query laravel 找到答案

Table: Users Columns:id,name,class_id

表:用户列:id,name,class_id

$users = DB::table('users')->whereIn('class_id', [1, 2, 3])->orderBy('name', 'ASC')->paginate(50);