Jaroslav Klimčík
Jaroslav Klimčík

Reputation: 4838

Laravel - artisan - cannot insert with null column

I have this table structure which I created partly with laravel builder:

public function up() {
    DB::statement('
        CREATE TABLE `tbl_permission` (
          `permission_id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
          `id_module` smallint(5) unsigned NOT NULL,
          `name` varchar(50) NOT NULL,
          `create` TINYINT NOT NULL DEFAULT 0,
          `view` TINYINT NOT NULL DEFAULT 0,
          `is_composition` tinyint(1) NOT NULL DEFAULT "0", 
          `suffix_czech_name` VARCHAR(100), 
          `permission_table` VARCHAR(50),   
          FOREIGN KEY (`id_module`) REFERENCES `tbl_modules` (`id_module`)
        ) COLLATE utf8_czech_ci;
    ');
}

then I have another migration with insert:

public function up() {
    DB::table('tbl_permission')->insert([
        ['name' => 'account_bad_rooms', 'id_module' => 1, 'create' => 0, 'view' => 1, 'is_composition' => 0, 'suffix_czech_name' => 'name'],
        ['name' => 'account', 'id_module' => 1, 'create' => 1, 'view' => 1, 'is_composition' => 0, 'suffix_czech_name' => 'name'],
        ['name' => 'accountRoomIdConfig', 'id_module' => 1, 'create' => 1, 'view' => 1, 'is_composition' => 0, 'suffix_czech_name' => 'name', 'permission_table' => 'accountRoomIdConfig']
    ]);
}

When I use migration then everything works without any error except I don't have any inserted data. I figured out that is because in two inserts I don't have column permission_table which can be null. When I add this column, then all inserts have same structure, migration is fine. Problem is that I have more than 70 inserts and some have column permission_table and some does not have it. Is somehow possible to insert all data without same structure?

Upvotes: 0

Views: 1163

Answers (1)

mdamia
mdamia

Reputation: 4557

If you do an insert without setting permission_table value you will get a sql error value list does not match column list. Even if default value is null. you still have to pass the column in all rows with a value of '' even if it does not have a value.

public function up() {
DB::table('tbl_permission')->insert([
    [
     'name' => 'account_bad_rooms', 
     'id_module' => 1, 
     'create' => 0, 
     'view' => 1, 
     'is_composition' => 0, 
     'suffix_czech_name' => 'name'
     'permission_table' => ''
    ],
    [ 
      .... next record
    ]

  ]);
}

Hope this help.

Upvotes: 1

Related Questions