Laravel 重新播种 table

Laravel reseeding a table

在 Laravel 中,您将如何重新播种数据库?不丢失现有数据/迁移?

我有一个 RoleAndPermissionSeeder.php 带有 Spatie 的许可包:

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleAndPermissionSeeder extends Seeder
{
    public function run()
    {
        // Reset cached roles and permissions
        app()[PermissionRegistrar::class]->forgetCachedPermissions();

        $permissions = [
            'articles create',
            'articles delete',
            'articles read',
            'articles update',
            'dashboard read',
        ];

        foreach ($permissions as $permission) {
            Permission::create(['name' => $permission]);
        }
        // =======================================================================

        $admin = Role::create(['name' => 'admin']);
        $member = Role::create(['name' => 'member']);
        Role::create(['name' => 'super-admin']);

        // =======================================================================

        $admin_permissions = [
            'articles read',
            'dashboard read',
        ];

        $member_permissions = [
            'dashboard read',
        ];

        $admin->syncPermissions($admin_permissions);
        $member->syncPermissions($member_permissions);
    }
}

为博客创建新的迁移后,我添加了额外的阅读、更新博客等权限。我将如何重新播种此文件以便添加新权限?

如果您的播种机 class 有 firstOrCreate 而不是 create

foreach ($permissions as $permission) {
    Permission::firstOrCreate(['name' => $permission]);
}
// =======================================================================
$admin = Role::firstOrCreate(['name' => 'admin']);
$member = Role::firstOrCreate(['name' => 'member']);
Role::firstOrCreate(['name' => 'super-admin']);

不会重复数据。如果syncPermissions在幕后使用sync,那应该不是问题。

只要不丢失 table,就不会丢失任何数据。