引用 yii2/codeception 数据文件中的夹具记录


Referencing fixture record in yii2/codeception data files

有没有办法在Yii2/Codeception ActiveFixture的夹具数据文件中指定另一个夹具的相关行?请考虑以下用户/配置文件关系示例:

用户.php:

return [
    'user1' => [
        'email' => 'user1@example.net',
     ]
];

简介.php:

use common'models'User;
return [
    'profile1' => [
        'user_id' => User::findOne(['email' => 'user1@example.net'])->id;
        'name' => 'My Name',
     ]
];

文档指出"您可以为行提供别名,以便在测试的后期,您可以通过别名引用该行。有没有办法引用另一个灯具内的行?例如,在配置文件中使用类似 $this->user('user1'(->id 之类的内容.php?我找不到任何关于如何做到这一点的提及。您如何创建这种相关夹具?

执行其 load() 方法后,只能在专用Fixture对象的 data 属性范围内访问别名数据。使此数据可从另一个Fixture对象的数据文件访问的唯一方法是将其注册到某个全局对象,例如Application对象。

我通常只是在构建依赖数据集之前查询所有需要的数据:

use common'models'User;
$users = User::find()->indexBy('email')->all();
return [
    'profile1' => [
        'user_id' => $users['user1@example.net']->id,
        'name' => 'My Name',
     ]
];

我将Faker与Yii2一起使用。当我开始编写测试时,我发现我需要好的夹具。在 yii2 中有 yii2-faker/FixtureController ,它可以生成夹具。文档中的更多内容

但我遇到了与作者相同的问题。我需要为用户、配置文件(包含user_id(和角色生成夹具。我没有在文档中找到解决方案,如何做到这一点,但这对我来说是有效的。

模板:用户.php

return [
'id' => $index +1 ,
'login' => $faker->unique()->safeEmail,
'password' => $user->hashPassword('123qwe'),
'type' => '0',
'is_active' => '1',
'is_verified' => '1',
'created_at' => time(),
'updated_at' => time(),

];

配置文件.php

return [
'id' => $index +1 ,
'user_id' => $index +1 ,
'first_name' => $faker->firstName,
'last_name' => $faker->lastName,
'middle_name' => $faker->optional()->firstName,
'phone' => $faker->unique()->phoneNumber,
'contact_email' => $faker->email

];

这里的主要特点是 - $index。

`$index`: the current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.

所以我可以知道用户中的 id 是什么并将其插入配置文件中。

之后,我运行命令:

php yii fixture/generate users profiles --count=100

并生成了 100 个具有配置文件的用户。我希望它对某人有所帮助。