在 Laravel 中将用户播种到数据库时出现问题

Problem with seeding users to database in Laravel

我正在尝试在数据库中播种用户,但我收到错误提示

Symfony\Component\Debug\Exception\FatalThrowableError  : Call to a member function random() on bool

我有用户 table 和性别 table 与 gender_id 在用户 table 中指向性别 table 中的男人或女人列具有许多关系.当我为数据库做种并创建新用户时,我希望能够在用户 table 中自动写入 gender_id。目前使用这段代码,我从上面得到了错误,并且在 gender_id 列中得到了 NULL,但其余的它在用户和性别 table 中都正确插入了。当我删除 random() 函数时,它总是在 gender_id 中插入 1,但我希望能够随机写入 1 或 2。此外,当我转储 $genders 时,它 returns TRUE。有什么办法可以解决这个问题,我们将不胜感激。这是我的代码。

UserSeeder.php

<?php

use Carbon\Carbon;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class UsersTableSeeder extends Seeder
{
    /**
    * Run the database seeds.
    *
    * @return void
    */
    public function run()
    {
        $genders = DB::table('genders')->insert([
            [
                'genders' => 'Woman',
            ],
            [
                'genders' => 'Woman Looking For Woman',
            ],
            [
                'genders' => 'Man',
            ]
        ]);

        //dd($genders);

        DB::table('users')->insert([
            'gender_id' => $genders->random(),
            'name' => 'authuser',
            'email' => 'authuser@auth.com',
            'email_verified_at' => now(),
            'password' => Hash::make('auth123456'),
            'age' => 18,
            'remember_token' => Str::random(10), 
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]); 
    }
}

用户table

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('gender_id')->nullable();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password')->default();
            $table->integer('age')->default()->nullable();
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

性别table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateGendersTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('genders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('genders');
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('genders');
    }
}

User.php

public function gender()
{
    return $this->belongsTo(Gender::class, 'gender_id', 'id');
}

Gender.php

public function users()
{
    return $this->hasMany(User::class, 'gender_id', 'id');
}

在你的用户创建方法中

而不是

'gender_id' => $genders->random(),

你可以用这个

'gender_id' => rand(1,3),

无需添加性别 here.You 可以在其他播种机中添加或手动添加 that.Here 您的性别 ID 应该在 1,2 和 3 中。fixed.THen 您可以使用rand() 函数 here.rand() 是一个 php 函数。rand() 定义一个随机数,您可以像 rand(min,max) 一样固定它的值,所以就在这里使用这个 rand(1,3 )

public function run()
    {

    $genders = DB::table('genders')->insert([
            [
                'genders' => 'Woman',
            ],
            [
                'genders' => 'Woman Looking For Woman',
            ],
            [
                'genders' => 'Man',
            ]
        ]);//your wish to seed this gender in here

        DB::table('users')->insert([
            'gender_id' => rand(1,3),
            'name' => 'authuser',
            'email' => 'authuser@auth.com',
            'email_verified_at' => now(),
            'password' => Hash::make('auth123456'),
            'age' => 18,
            'remember_token' => Str::random(10), 
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]); 
    }

你可以从 Gendre 中提取你的 id 值,然后像这样随机地做:

$genders = DB::table('genders')->insert([
            ['genders' => 'Woman'],
            ['genders' => 'Woman Looking For Woman'],
            ['genders' => 'Man']
        ]);
$gendreIds = Genders::pluck('id');

DB::table('users')->insert([
            'gender_id' => $gendreIds->random(),
            ...
]); 

这将为您提供数据库中存在的性别。

有时 seed 不会给你 id 从 1 到 3。

所以我认为使用 rand(1,3) 不是最佳解决方案。

祝你好运!