Laravel的工厂模型关系

时间:2018-01-03 13:10:04

标签: laravel foreign-keys factory faker laravel-seeding

我有2个名为用户 Users_meta 的表。两者都在分享一对一关系。我想在播种的帮助下插入虚拟数据。我能做到这一点,唯一让我发疯的是,我无法在user_id作为外键的用户和users_meta表之间建立关系。我尝试了几种方法但是要么使用相同的 user_id 创建重复的entires,要么不断重复相同的user_id。

我到底想要的是什么;在创建例如100条记录时,在插入第一条用户记录后,应该使用相同的用户 user_ID ,将其添加到 users_meta 表格 user_id 字段并重复插入,直到100个假记录。

非常感谢对此的任何帮助

代码位于:UserFactory.php

$factory->define(App\User::class, function (Faker $faker) {
static $password;

return [
    'username' => $faker->userName,
    'email' => $faker->unique()->safeEmail,
    'password' => $password ?: $password = bcrypt('secret'),
    'referral_code' => str_random(10),
    'referred_by_code' => str_random(10),
    'role'  => $faker->randomElement(['administrator', 'user', 'volunteer']),
    'remember_token' => str_random(10),
]; });

代码:UsersMetaFactory.php

$factory->define(App\Usersmeta::class, function (Faker $faker) {

return [
    'user_id'   =>  $faker->randomElement(\App\User::pluck('id')->toArray()),
    'first_name' => $faker->firstname,
    'last_name' => $faker->lastname,
    'gender' => $faker->randomElement(['male', 'female']),
    'date_of_birth' =>  $faker->dateTimeThisCentury->format('Y-m-d'),
    'address'   =>  $faker->address,
    'city'  =>  $faker->city,
    'state' =>  $faker->state,
    'zip_code'  =>  $faker->postcode,
    'country'   =>  $faker->country,
    'cell_phone'    =>  $faker->e164PhoneNumber,
    'bitcoin_address' => str_random(16),
    'monero_address'    =>  str_random(16),
    'security_question' =>  $faker->realText($maxNbChars = 20, $indexSize = 2),
    'security_answer'   =>  $faker->realText($maxNbChars = 40, $indexSize = 2),
    'is_founder'    =>  $faker->boolean($chanceOfGettingTrue = 50),
    'status'    =>  $faker->randomElement(['active', 'inactive']),
    'terms' =>  $faker->boolean
]; });

randomElement()方法为我提供了违反一对一关系主体的随机ID,我的应用程序崩溃了。我希望它应该从users表中获取id并将与user_id相同的id传递给users_meta表并继续生成虚假记录。

CreateUsersTable迁移类

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('password');
        $table->string('referral_code')->unique();
        $table->string('referred_by_code');
        $table->enum('role', ['administrator', 'user', 'volunteer'])->nullable();
        $table->rememberToken();
        $table->timestamps();
    });
}

CreateUsersMetaTable迁移类

public function up()
{
    Schema::create('users_meta', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('first_name');
        $table->string('last_name');
        $table->enum('gender', ['male', 'female'])->nullable();
        $table->string('date_of_birth')->nullable();
        $table->string('address')->nullable();
        $table->string('city')->nullable();
        $table->string('state')->nullable();
        $table->string('zip_code')->nullable();
        $table->string('country');
        $table->string('cell_phone');
        $table->string('bitcoin_address')->nullable();
        $table->string('monero_address')->nullable();
        $table->string('security_question');
        $table->string('security_answer');
        $table->string('is_founder')->nullable();
        $table->enum('status', ['active', 'inactive'])->nullable();
        $table->string('terms');
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users_meta');
    Schema::enableForeignKeyConstraints();
}

1 个答案:

答案 0 :(得分:1)

你应该删除这一行:

'user_id' => $faker->randomElement(\App\User::pluck('id')->toArray()),

在创建新模型时使用关系。这是一个经过修改的示例from the docs

factory(App\User::class, 50)->create()->each(function ($u) {
    $u->usersmeta()->save(factory(App\Usersmeta::class)->make());
});