codeigniter4 / CodeIgniter4

Open Source PHP Framework (originally from EllisLab)
https://codeigniter.com/
MIT License
5.4k stars 1.9k forks source link

Bug: Model cannot insertBatch when $useAutoIncrement is false #7744

Closed MaulanaMalikS closed 1 year ago

MaulanaMalikS commented 1 year ago

PHP Version

8.2

CodeIgniter4 Version

v4.3.3

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

Windows

Which server did you use?

cli-server (PHP built-in webserver)

Database

No response

What happened?

Model cannot insert using insertBatch when $useAutoIncrement is set to false.

It's exactly the same as this issue: https://forum.codeigniter.com/showthread.php?tid=84733

But it occurs in insertBatch.

Steps to Reproduce

  1. Create a model, set $useAutoIncrement to false, and exclude $primaryKey from $allowedFields as mentioned in the docs.

  2. Instantiate model, $model = model(MyModel::class);

  3. Utilize the $model->insertBatch($data); method to insert data, including the primary key.

Expected Output

The data should be inserted into the database.

Anything else?

https://forum.codeigniter.com/showthread.php?tid=84733

kenjis commented 1 year ago

I've confirmed this bug.

CodeIgniter\Database\Exceptions\DataException : There is no primary key defined when trying to make insertBatch.

--- a/tests/system/Models/InsertModelTest.php
+++ b/tests/system/Models/InsertModelTest.php
@@ -65,6 +65,26 @@ final class InsertModelTest extends LiveModelTestCase
         $this->seeInDatabase('job', ['name' => 'Cab Driver']);
     }

+    public function testInsertBatchUseAutoIncrementSetToFalse(): void
+    {
+        $insertData = [
+            [
+                'key'   => 'key1',
+                'value' => 'value1',
+            ],
+            [
+                'key'   => 'key2',
+                'value' => 'value2',
+            ],
+        ];
+
+        $this->createModel(WithoutAutoIncrementModel::class);
+        $this->model->insertBatch($insertData);
+
+        $this->seeInDatabase('without_auto_increment', ['key' => 'key1']);
+        $this->seeInDatabase('without_auto_increment', ['key' => 'key2']);
+    }
+
     public function testInsertBatchValidationFail(): void
     {
         $jobData = [
kenjis commented 1 year ago

@MaulanaMalikS I sent #7759. Try it if you can.

MaulanaMalikS commented 1 year ago

@kenjis, yes, I've tried it and it works!