Basically I have users who belongs to many users. We can imagine friendship relations between users.
So I have a pivot table for the relation, with the id's of 2 users and one additionnal field 'created_at'.
users table: id, name
friend_user table : user_id, friend_id, created_at
In my User model, i have a friends function which returns a collection of users :
public function friends() {
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id');
}
My goal is to get the list of every relation between users. With a loop on User::all(), I can easily get all those relations, user after user :
$users = User::all();
foreach ( $users as $user ) {
foreach ( $user->friends as $friend ) {
return [$user->name . 'is friend with ' . $friend->name];
}
}
But I would like to get them ordered by 'created_at', indifferently the user who is in the relation.
Is there an easy way to do this with eloquent or maybe another way ?
Thanks for your help.
CodePudding user response:
you can use pivot table fields with the alias pivot
$user = User::with(['friends' => function($friendQuery) {
$friendQuery->orderBy('pivot.created_at', 'desc');
}])->get();
CodePudding user response:
You can try with
User::orderBy('created_at')->get();
or if you reffer to relation, you can do the same in the relationship
public function friends() {
return $this->belongsToMany(User::class, 'friend_user', 'user_id', 'friend_id')->orderBy('created_at');}
CodePudding user response:
may be this helps to you first change your function into this
public function friends() {
return $this->belongsToMany(Friend::class);
}
then in controler do this
$users = User::with('friends')->get();
foreach ( $users as $user ) {
return [$user->name . 'is friend with ' . $user->firends->name];
}
use dd($users) to check whether you find a friends relation or not.
