Laravel Eloquent `take` and `orderBy`

2019-07-18 04:49发布

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条回答
2楼-- · 2019-07-18 05:44

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.

查看更多
登录 后发表回答