Laravel Eloquent中不存在orderBy方法吗? [英] Method orderBy does not exist in Laravel Eloquent?

查看:303
本文介绍了Laravel Eloquent中不存在orderBy方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段这样的代码:

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

我遇到以下错误:

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

我猜orderBy需要直接跟随Product::,但是我无法保存$products = Product::,可以吗?

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

有什么建议吗?谢谢.

推荐答案

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

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

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

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

这篇关于Laravel Eloquent中不存在orderBy方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆