I want to test the memberOfTeam relationship from the User model using factories. According to the Laravel document, I should use for, but it doesn't work and it creates 3 users with team_id as null for me. (team_id is nullable by default.)
How can I solve this problem using factories?
laravel:10 php:8.1
in User Model:
public function memberOfTeam(): BelongsTo
{
return $this->belongsTo(
Team::class ,
'id' ,
self::TEAM_ID
);
}
in Team model:
public function members(): HasMany
{
return $this->hasMany(User::class, User::TEAM_ID);
}
Each team needs a user_id to be created, which is the manager of that team.
in tests/Feature/Model/UserTest:
$count = 3;
$team = Team::factory()
->for($this->makeUser(), TeamRelation::MANAGER)
->create();
$user = $this->makeUser()
->count($count)
->for($team, UserRelation::MEMBER_OF_TEAM)
->create();