braindamage
braindamage

Reputation: 2266

ORM: friendship/buddylist relationship

I'm trying to use ORM for the first time, I've defined the models like this:

User model:

class User extends Eloquent
{
    public function friends()
    {
       return $this->has_many_and_belongs_to('User', 'friends', 'user1_id', 'user2_id');
    }    
}

Friend model:

class Friend extends Eloquent
{
    public function friend()
    {
        return $this->belongs_to('User', 'user_id');
    }    
}

Friends mysql table:

id (pkey) # user1_id (references users.user_id) # user2_id (references users.user_id)

Right now by using $user->friends I get a unilateral list because the friends database parameters could be in any order (user1 is friend of user2 OR user2 is friend of user1). This would be ok if I was trying to use following/followers approach, but I want it to be reciprocal.

What is the best way to do this kinda of stuff? Inserting duplicated user1/user2 and user2/user1 on the database doesn't sound like a good approach and I wouldn't even know how to translate this to the ORM. Also, it seems the Friend model is not being used/getting called at all.

I'm also going to have a similar problem on the invite friend system.

Upvotes: 4

Views: 717

Answers (1)

Matija
Matija

Reputation: 2720

You are looking for a Many to Many relationship, between Users! Check out how you can do this in Doctrine: Doctrine - Many to Many Self Referencing. Doctrine example might help you to get started.

The idea is that you have one Entity, Users, and they can be friends with each other.

Upvotes: 2

Related Questions