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.
Mar 30, 2023
3
Level 8
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
Please or to participate in this conversation.