【问题标题】:Factory model relationships in LaravelLaravel 中的工厂模型关系
【发布时间】:2018-06-13 04:02:35
【问题描述】:

我有 2 个名为 Users 和 Users_meta 的表。两者都共享一对一关系。我想在播种的帮助下插入虚拟数据。我能够做到这一点,唯一让我发疯的是,我无法以 user_id 作为外键建立用户和 users_meta 表之间的关系。我尝试了几种方法,但要么使用相同的 user_id 创建重复的整体,要么不断重复相同的 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();
}

【问题讨论】:

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


    【解决方案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());
    });
    

    【讨论】:

    • 您的解决方案完全符合我的需要。但现在我遇到另一个问题终端给出消息: SQLSTATE [HY000]:一般错误:1364 字段'user_id'没有默认值。更新我有问题的迁移表做检查。
    • @ChetanChitte 我认为这段代码不会导致错误,因为$u->usersmeta() 正在设置user_id。请检查究竟是什么代码导致了错误。
    • 您的回答确实解决了问题。这可能是另一个问题。只有终端抛出此错误,其余一切看起来都正常。
    • 很高兴它有帮助。
    猜你喜欢
    • 2015-12-09
    • 2017-03-21
    • 2020-03-09
    • 2021-11-06
    • 2018-01-10
    • 2021-06-29
    • 2018-08-11
    • 1970-01-01
    • 2015-10-21
    相关资源
    最近更新 更多