1

I'm facing some issues in establishing relationships amongst User, Clan, and Clan Member models. I have three models in which I have defined the relationship as...

Clan model

public function clanMembers() {
    return $this->hasMany('App\ClanMember', 'clan_id', 'clan_id');
}

ClanMember model

public function clan() {
    return $this->belongsTo('App\Clan', 'clan_id', 'clan_id');
}

I am trying to get Clan details of a requested user and his other Clan Members. I am using the following:

$clanMembers = ClanMember::find(Auth::user()->id)->clan()->with('clanMembers')->get();

From the above, I am getting the response correct.

"data": [
        {
            "id": 2,
            "clan_leader_id": 3,
            "clan_name": "@rockers1",
            "clan_avatar": "",
            "game_id": 1,
            "max_members_count": 50,
            "clan_id": "1505ccd15b01",
            "created_at": "2019-05-04 04:31:44",
            "updated_at": "2019-05-04 04:31:44",
            "clan_leader_name": "" 
            "clan_members": [
                {
                    "id": 2,
                    "user_id": 2,
                    "clan_id": "1505ccd15b01",
                    "role_id": 2,
                    "status": 0,
                    "created_at": "2019-05-04 04:33:03",
                    "updated_at": "2019-05-04 04:33:03"
                }
            ]
        }
    ]

Now I want to establish a relationship between the User and Clan model which has id and clan_leader_id as a foreign key to get clan_leader_name from User table in Clan model and user_name in place of user_id in clan_members. Clan member has user_id and id with the user as a foreign key.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95

1 Answers1

1

Check out many-to-many relationships. Your models/tables should be: User, Clan, and ClanUser, where clan_user is an intermediate pivot table containing clan_id and user_id.

Your Clan model should contain the following relationship

public function users()
{
    return $this->belongsToMany('App\User');
}

And your User model should contain the following relationship

public function clans()
{
    return $this->belongsToMany('App\Clan');
}

To get a list of clans for a user:

$clans = User::find($userId)->clans()->get();

To get a list of users for a clan:

$users = Clan::find($id)->users()->get();
Dwight
  • 12,120
  • 6
  • 51
  • 64
hunter
  • 872
  • 10
  • 26