繁体   English   中英

在 Laravel 中将用户播种到数据库的问题

[英]Problem with seeding users to database in Laravel

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

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

我有用户表和性别表,在用户表中带有gender_id,指向具有hasMany关系的性别表中的男人或女人列。 当我播种数据库并创建新用户时,我希望能够在用户表中自动写入gender_id。 目前,使用此代码,我从上面得到该错误,并在gender_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' => '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(),
        ]); 
    }
}

用户表

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

用户名

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

性别.php

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

在您的用户创建方法中

代替

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

你可以用这个

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

您可以从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)不是最好的解决方案。

祝你好运!

无需在此处添加性别。您可以在其他播种机中执行此操作或手动执行此操作。在这里,您的性别 ID 应该在 1,2 和 3 中。固定。然后您可以在这里使用 rand() 函数。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(),
        ]); 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM