What is the best way to model friendships with an eloquent one? My table layout is below, and I would like to define one relationship in which I could get all the friends, for example, as follows.
<?php class User extends Eloquent { public function friends() { return $this->belongsToMany('User', 'friendships', 'user_id', 'friend_id')->orWhere($this->id,'=', 'friend_id'); } } +----+---------+-----------+----------+---------------------+---------------------+ | id | user_id | friend_id | state | created_at | updated_at | +----+---------+-----------+----------+---------------------+---------------------+ | 1 | 3 | 1 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | | 2 | 2 | 3 | accepted | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | +----+---------+-----------+----------+---------------------+---------------------+
The ratio above is close to work when I'm looking for friends with user id 3 I get users 1 and 3, but obviously I want 1 and 2.
Friendship table
user_id: ID of the user who requested friendship
friend_id: Target friend user id
state whether the friendship is waiting, accepted or blocked.
created_at and updated_at
I know there are solutions from Laravel. Many of the many links to the lookup table work in only one direction , where I can find friends on both sides of the relationship, but I have to have two lines, for example, if users 1 and 3 are friends, then on the same line user_id = 3 and friend_id = 1, and in the next line, vice versa. (Or, if I don't have two lines, I have to execute two queries).
php orm laravel laravel-4
Thomas clarkson
source share