ORM: friendship / Buddhist relationship

I am trying to use ORM for the first time, I defined the models as follows:

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'); } } 

Mysql table friends:

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

Right now, using $user->friends , I get a one-way list, because the friends database parameters can be in any order (user1 is a friend of user2 OR user2 is a friend of user1). It would be normal if I tried to use a followers / followers approach, but I want it to be reciprocal.

What is the best way to do this? Inserting duplicate user1 / user2 and user2 / user1 into the database doesn't seem like a good approach, and I don't even know how to translate this into ORM. In addition, it seems that the Friend model is not used / not called at all.

I will also have a similar problem in the invite friends system.

+4
source share
1 answer

You are looking for Many to Many relationships, between Users! See how you can do this in the Doctrine: Doctrine is many to many . An example of a doctrine can help you get started.

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

+2
source

Source: https://habr.com/ru/post/1444877/


All Articles