Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AlexHupe's avatar

Use $this->id in relation

Hello,

I have 3 Models: Account, User, Role

Every user could be in different accounts und can have multiple roles in different accounts, e.g. a player(Role-ID 12) in Account 1 and a coach(Role-ID 13) in Account 2.

class Account extends Model
{
public function players(){
        return $this->belongsToMany('App\User')
           ->whereHas('roles', function ($q) {
                $q->where('role_id', 12)->where('account_id', $this->id);
            });
    }
}

Here is the User-Model:

class User extends Model {
    public function roles()
    {
        return $this->belongsToMany(\App\Role::class);
    }
}

Now I will get all players from an account. This works:

$account = Account::findOrfail(2);
$account->players->count(); // 182

Now I will get all players from an account. This works not:

$account = Account::with('players')->findOrfail(2);
$account->players->count(); // 0

I suspect, that I cannot use $this in the relation if I use eager loading. But how can I get the right role for the user.

Thank you for your help!

Alex

0 likes
3 replies
abd_wazzan's avatar

I agree with you that the relation could not see the mode id using "$this->id" because the data already loaded when you used Account::with('player'), and you can test that theory by hard coding the account id in the relation.

cwhite's avatar

Why do you need the account_id clause on the Account model in the first place?

You could try using whereColumn but I suspect your relations are configured wrong...you haven't shown the Role model

AlexHupe's avatar

@cwhite thank you for your help!

the role-model is very clear:

ID  |  name
12  |  player
13  |  coach

of course is there a account_user - table:

user_id | account_id 
1 | 1
1 | 2

this is the user_role - table

role_id | user_id | account_id
12 | 1 | 1 
13 | 1 | 2 

(User 1 is in Account 1 a player and in Account 2 an coach)

My problem is, the relation between user, account and account-specific role. Is there a better way?

Please or to participate in this conversation.