简体   繁体   中英

Laravel sort by a relationship in Eloquent

Many to many relationship between users and reports. Any user can have many reports. I want to sort the reports for a user by the created_at column. How would i finish this below to do that??

$x = User::find(1)->report.....

For anyone wondering, you add parenthesis to the end of a relationship method when you are chaining on a function like orderBy() you leave it off when you just want the collection. IF you need to alter the returned collection by sorting or something you would add parenthesis because you are in fact ADDING(CHAINING) another method behind the relationship.

$x = User::find(1)->reports()->orderBy('created_at')->get();

See the doc . Also here

From the second link:

Once the relationship is defined, you may access the user's roles using the roles dynamic property:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    //
}

Of course, like all other relationship types, you may call the roles method to continue chaining query constraints onto the relationship:

$roles = App\User::find(1)->roles()->orderBy('name')->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM