-1

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.

3 Answers3

0

you can use pivot table fields with the alias pivot

$user = User::with(['friends' => function($friendQuery) {
    $friendQuery->orderBy('pivot.created_at', 'desc');
}])->get();
N69S
  • 16,110
  • 3
  • 22
  • 36
  • Return a SQLState "Column not found: 1054 Unknown column 'pivot.created_at' in 'order clause'". What does return this query for you ? – Yann Pollet Jan 07 '22 at 09:17
0

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');}
  • Thanks, but this function returns me the friends of 1 user, and I need to get all the rows of the friend_user table, not just those refering of a particular user. – Yann Pollet Jan 07 '22 at 09:02
0

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.

Umer Fayyaz
  • 357
  • 3
  • 12