Laravel 5.8 使用多对多关系播种数据库

Laravel 5.8 seeding database with many to many relations

我目前使用 Laravel 5.8,我的数据库有一个 users table 和一个 roles table,它们由多对多关系连接。我的意图是使用 php artisan migrate:fresh --seed 一次性为整个数据库播种,但是 pivot table role_user 总是空的,这表明 attach/sync 有问题。我打算实施更多的多对多关系,所以我想彻底了解使用播种机和工厂播种这些关系。

如何播种多对多关系并快速检查这些关系是否正常工作?

用户模型:

    class User extends Authenticatable
    {
        //Default variables generated by Laravel
        public function roles()
        {
           return $this->belongsToMany('App\Role', 'role_user')->withTimestamps();
        }
    }

榜样:

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User', 'role_user')->withTimestamps();
    }
}

Table role_user 迁移:

  public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('role_id');
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
    }

角色播种者:

public function run()
{
    $role_user = new Role();
    $role_user->role = 'user';
    $role_user->save();

    $role_admin = new Role();
    $role_admin->role = 'admin';
    $role_admin->save();
}

用户播种者:

 public function run()
    {
        $faker = Faker\Factory::create();

        $role_user = Role::where('role','=','user')->first();
        $role_admin  = Role::where('role','=','admin')->first();

        //Generic user account for testing
        $test_user = new User();
        $test_user->username = 'user';
        $test_user->email = 'user@example.com';
        $test_user->email_verified_at = now();
        $test_user->password = 'user';
        $test_user->remember_token = Str::random(10);
        $test_user->save();
        $test_user->roles()->attach($role_user);

        //Generic admin account for testing
        $test_admin = new User();
        $test_admin->username = 'admin';
        $test_admin->email = 'admin@example.com';
        $test_admin->email_verified_at = now();
        $test_admin->password = 'admin';
        $test_admin->remember_token = Str::random(10);
        $test_admin->save();
        $test_admin->roles()->attach($role_admin);
    }

如果您想通过工厂使用,

在 factory 文件夹中创建 UserFactory.php

<?php

use App\User;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'username'           => $faker->name , 
        'email'              => $faker->unique()->safeEmail , 
        'email_verified_at ' => Str::random(10),
        'remember_token'     => now(),
        'password'           => Hash::make('123456')
    ];
});

然后创建RoleUsersFactory.php

<?php

use App\User,App\Role,App\RoleUser;
use Illuminate\Support\Str;
use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$factory->define(App\RoleUser::class, function (Faker $faker) {
    return [
        'role_id'   => Role::all()->random()->id,
        'user_id'   => User::all()->random()->id,
    ];
});

然后在你的 DatabaseSeeder.php 添加此

factory(App\User::class, 50)->create()->each(function($u) {
    $u->userroles()->save(factory(App\RoleUser::class)->make());
 });

您还需要创建 RoleUser 模型,但在用户模型中您设置了不正确的关系 role_user 您的角色中不存在 table。

希望对您有所帮助