Laravel Eloquent `take` 和 `orderBy`

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

Laravel Eloquent `take` and `orderBy`

laravellaravel-5laravel-eloquent

提问by Einsamer

When I try to use each of "take" and "orderBy" query, the Model return some records:

当我尝试使用每个“take”和“orderBy”查询时,模型返回一些记录:

$this->hasMany("App\User")->take(3)

$this->hasMany("App\User")->take(3)

$this->hasMany("App\User")->orderBy("id", "desc")

$this->hasMany("App\User")->orderBy("id", "desc")

But when I combine them, it return a null array:

但是当我组合它们时,它返回一个空数组:

$this->hasMany("App\User")->take(3)->orderBy("id", "desc")

I run the original sql (from toSql() function) and it return 3 records as I expect. What mistake I get?

我运行原始 sql(来自 toSql() 函数)并按我的预期返回 3 条记录。我得到了什么错误?

回答by Robin Dirksen

You need to change the order, it will be:

您需要更改顺序,它将是:

$this->hasMany("App\User")->orderBy("id", "desc")->take(3)

This ->take(3)will execute the mysql query, so you first need to add the orderBy("id", "desc")to the hasMany relation.

->take(3)将执行 mysql 查询,因此您首先需要将 加入orderBy("id", "desc")到 hasMany 关系中。