Cách seeder table có foreign key trong PGSQL Laravel

administrator

Administrator
Nhân viên
9 Tháng tám 2021
87
0
6
1. Xóa foreign key profile_id ở table users:
Mã:
ALTER TABLE users
    DROP CONSTRAINT user_profile_id_foreign
2. Xóa dữ liệu ở bảng cần seeder:
Mã:
TRUNCATE TABLE profiles;
3. insert dữ liệu trong file seerder:
Mã:
php artisan db:seed --class=ProfileSeeder
4. Tạo lại khóa ngoại oreign key profile_id ở table users:
Mã:
ALTER TABLE users
ADD CONSTRAINT user_profile_id_foreign FOREIGN KEY (profile_id) REFERENCES profiles (id);

Code sheeder Laravel:
Mã:
        DB::unprepared('ALTER TABLE users DROP CONSTRAINT cv_profile_id_foreign');
        DB::table('profiles')->truncate();
        DB::table('profiles')->insert([
            [
                'id' => '1',
                'name' => 'Tran Van Ten',
            ],
            [
                'id' => '2',
                'name' => 'Nguyen Van A',
            ],
        ]);
        DB::unprepared('ALTER TABLE cv ADD CONSTRAINT cv_profile_id_foreign FOREIGN KEY (profile_id) REFERENCES profies (id)');
 
Chỉnh sửa lần cuối: