Kiwi
Kiwi

Reputation: 2773

laravel 5 pivot table

I'm trying to implement a friendlist for a user so a user can have many friends

but for calling the friends I'm having trouble getting my relation right:

user
  id

friends
  user_id
  friend_user_id

Class user:

public function Friends(){
    return $this->hasMany('App\User', 'friends');
}

So Auth::User()->Friends should return a list of User models

Upvotes: 0

Views: 2397

Answers (3)

Ray
Ray

Reputation: 649

In your user class, define the function as follows:

public function Friends(){
    return $this->hasMany('friends');
}

Calling $user->Friends()->get() should return you everything you need. Note that 'friends' should be the name of the table.

Upvotes: 0

Allmighty
Allmighty

Reputation: 1519

When creating a relation to the same model, you would do something like this:

Models/User.cs

public function Friends()
{
   return $this->hasMany('User', 'user_friend_of', 'id'); // assuming user_friend_of is the FK on user-table
}

public function User()
{
    return $this->belongsTo('User');
}

This would mean you have only 1 table, which has a foreign key to another row in the same table, for instance: (id - name - user_friend_of )

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152860

You actually don't have a "one to many" relationship but rather "many to many" with friends being your joining table

Try this:

public function Friends(){
    return $this->belongsToMany('App\User', 'friends', 'user_id', 'friend_user_id');
}

Upvotes: 1

Related Questions