在Laravel中将用户植入数据库的问题

时间:2019-12-18 12:06:01

标签: php laravel laravel-seeding

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

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

我在用户表中有用户表和性别表,其性别为id,指向具有hasMany关系的性别表中的“男人”或“女人”列。我希望能够在为数据库添加种子并创建新用户时自动在用户表中写入sex_id。目前,使用此代码,我从上面得到了该错误,并且在gender_id列中为NULL,但是让它在用户和性别表中正确插入。当我删除random()函数时,它总是在sex_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');
    }
}

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

3 个答案:

答案 0 :(得分:1)

使用您的用户创建方法

代替

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

您可以使用此

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

答案 1 :(得分:1)

无需在此处添加性别。您可以在其他播种机中进行添加或手动执行此操作。此处您的性别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(),
        ]); 
    }

答案 2 :(得分:1)

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

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

有时候种子不会给您ID从1到3。

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

祝你好运!