Friendship system with Laravel : Many to Many relationship

前端 未结 2 1715
夕颜
夕颜 2020-11-27 03:48

I\'m trying to create a Friendship system with Laravel (I\'m starting with it) but I\'m blocked with relationships. Here\'s the thing : there is one table Users and one tabl

2条回答
  •  南方客
    南方客 (楼主)
    2020-11-27 03:51

    It's oviously a problem in your DB and also definition of the relation. Many-to-Many relation type expects you to use and intermediate table. Here's what you have to do :

    1. Create a user_friend (id, user_id, friend_id) table in your schema.
    2. Remove unnecessary fields from user and friend tables.
    3. Create proper foreign keys . user.id-> user_friend.user_id , friend.id -> user_friend.friend_id
    4. Better define full relation on the User and Friend models,

    for example :

     class User extends Eloquent {
        function friends()
        {
            return $this->belongsToMany('User', 'user_friend', 'user_id', 'friend_id');
        }
    }
    

    You can read much more in Laravel docs, HERE

提交回复
热议问题