Laravel Eloquent `take` and `orderBy`

爱⌒轻易说出口 提交于 2020-01-15 08:20:46

问题


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

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

$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?


回答1:


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.



来源:https://stackoverflow.com/questions/42922008/laravel-eloquent-take-and-orderby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!