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

标签 php laravel laravel-seeding

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

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

我有用户表和性别表,用户表中的 sex_id 指向性别表中具有 hasMany 关系的 Man 或 Woman 列。当我播种数据库并创建新用户时,我希望能够在用户表中自动写入性别 ID。目前,使用此代码,我从上面得到了该错误,并且在 sex_id 列中得到了 NULL,但其余的它会正确插入到用户和性别表中。当我删除 random() 函数时,它总是在性别 ID 中插入 1,但我希望能够随机写入 1 或 2。另外,当我转储 $genders 时,它会返回 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' => '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e8899d9c809d9b8d9aa8899d9c80c68b8785" rel="noreferrer noopener nofollow">[email protected]</a>',
            'email_verified_at' => now(),
            'password' => Hash::make('auth123456'),
            'age' => 18,
            'remember_token' => Str::random(10), 
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]); 
    }
}

用户表

<?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');
    }
}

性别表

<?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');
    }
}

用户.php

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

性别.php

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

最佳答案

您可以从 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(),
            ...
]); 

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

有时种子不会给你 1 到 3 的 id。

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

祝你好运!

关于php - 在 Laravel 中将用户播种到数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59391682/

相关文章:

php - 使用 while 循环将 MySQL 结果分离到 Div 中

php - 在AWS S3存储桶中上传图像为0字节

php - Laravel 5 Eloquent 不在数据库中存储特殊字符

php - Laravel :"php artisan db:seed"不工作

php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?

php - 将 PHP 二维数组转换为 PHP 扩展

php - Laravel 迁移重命名可为空的字段解决方法?

php - Laravel 查询关系

laravel - 数据库在 Laravel 5 中使用 --force 进行生产时陷入迁移困境