Suppose I have a relation (1:1, 1:n, n:m). For example a User
with a UserProfile
where the profile_id
is stored in the User
model and is allowed to be NULL
if the user has no profile. Lets further assume I have two fixture classes (UserFixture
and UserProfileFixture
respectively).
In my fixtures I would therefore declare UserFixture::$depends = [UserProfileFixture::class]
. A data file for UserProfileFixture
could then look as follows:
user_profile.php:
return [
'profile-1' => ['gender' => 'male', 'birthday' => '1908-12-12 11:11:11'],
'profile-2' => ['gender' => 'female', 'birthday' => '1910-10-10 12:12:12'],
];
However, I couldnāt find any information on how to retrieve the auto-generated primary-key from the data file of UserFixture
:
user.php:
return [
'user-1' => ['username' => 'User 1', 'profile_id' => ???],
];
How am I supposed to access auto-generated values (like primary key) from UserProfileFixture
?
The best solution that I could think about was to set a singleton variable in beforeLoad()
like this:
UserProfileFixture.php
public function beforeLoad()
{
static::$instance = $this;
}
With this, I am able to retrieve the AR of profile-1
inside user.php as follows:
user.php:
$userProfile = UserProfileFixture::$instance;
return [
'user-1' => ['username' => 'User 1', 'profile_id' => $userProfile->getModel('profile-1')],
];
Am I missing something, or is Yii really not providing access to the instances of dependent fixtures out of the box?