سؤال

I have a user's table for my application. I also have a pivot table for people who add other people to the application. I am trying to list out all the users that have been added by a user (1). How can I write this in eloquent?

Select u.* FROM users u join friend_user f ON u.user_id = f.friend_id where f.user_id = 1

I have it in a Friend model that presents the pivot table. Is it better to have a full query there or to create a friend function in the User and Friend class to show relationships?

<in User model> public function Friend(){ return $this->belongsTo('User'); }
هل كانت مفيدة؟

المحلول

If I understood you correctly, you should have the following in your User model:

public function friends()
{
    return $this->belongsToMany('User', 'user_has_friends', 'user_id', 'friend_id');
}

Of course modify accordingly to your needs.

Now you can grab friends like this:

$user = User::find(1);

foreach($user->friends as $friend)
{
    echo $friend->name .'<br>';
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top