php Laravel Eloquent 中不存在方法 orderBy?

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

Method orderBy does not exist in Laravel Eloquent?

phplaraveleloquent

提问by Harrison

I have a piece of code like this:

我有一段这样的代码:

$products = Product::all()

if ($search_value) {
    $products = $products->where('name', 'LIKE', "%$search_value%");
}

$products = $products->orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();

I got the following error:

我收到以下错误:

BadMethodCallException in Macroable.php line 81:
Method orderBy does not exist.

I guess orderByneed to follow Product::directly, but I can't save $products = Product::, can I?

我想orderBy需要Product::直接关注,但我无法保存$products = Product::,可以吗?

Any suggestions? Thanks.

有什么建议?谢谢。

回答by Alexey Mezenin

You're trying to use orderBy()method on Eloquent collection. Try to use sortByDesc()instead.

您正在尝试orderBy()在 Eloquent 集合上使用方法。尝试使用sortByDesc()

Alternatively, you could change $products = Product::all();to $products = new Product();. Then all your code will work as you expect.

或者,您可以更改$products = Product::all();$products = new Product();. 然后您的所有代码都将按您的预期工作。

回答by gaurav

just use the one line code it will work fine

只需使用一行代码即可正常工作

$product= Product::orderBy('created_at','desc')->get();

回答by Pushpendra Pal

If you want to get the list of all data and grab it in descending order try this:

如果您想获取所有数据的列表并按降序获取,请尝试以下操作:

$post = Post::orderBy('id', 'DESC')->get();

回答by Bilawal Awan

use sortByDesc('id')or simple sortBy()inside use the variable through which you wanna sort like i add id

在里面使用sortByDesc('id')或简单的sortBy()使用你想要排序的变量,就像我添加 id

回答by Viral M

$table_Data = DB::table('tbl_product')->orderBy('id','DESC');

You can use this...

你可以用这个...

回答by KuKeC

You are first getting all()data and then trying to sort which is wrong. You have to fix this by removing

您首先获取all()数据,然后尝试对错误进行排序。你必须通过删除来解决这个问题

$products = Product::all()

and changing your code into something like this

并将您的代码更改为这样的内容

if ($search_value) {
    $products = Product::where('name', 'LIKE', "%$search_value%");
}
else {
    $products = Product::orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
}

Hope you get idea to tweak your code.

希望你有想法来调整你的代码。

回答by Himanshu Raval

Your query is wrong.

您的查询是错误的。

remove all from $products = Product::all()and then put get()at the end of your query.

remove all from$products = Product::all()然后放在get()查询的末尾。