简体   繁体   中英

How to get insert id after save to database in CodeIgniter 4

I'm using Codeigniter 4.

And inserting new data like this,

$data = [
        'username' => 'darth',
        'email'    => 'd.vader@theempire.com'
];

$userModel->save($data);

Which is mentioned here: CodeIgniter's Model reference

It's doing the insertion. But I haven't found any reference about to get the inserted id after insertion.

Please help. Thanks in advance.

This also works.

       $user= new UserModel();

        $data = [
                 'username' => 'darth',
                  'email'    => 'd.vader@theempire.com'
              ];

        $user->insert($data);
        $user_id = $user->getInsertID();

I got a simple solution after researching on the core of the CI 4 framework.

$db = db_connect('default'); 
$builder = $db->table('myTable');

$data = [
        'username' => 'darth',
        'email'    => 'd.vader@theempire.com'
];

$builder->insert($data);
echo $db->insertID();

Hope they'll add a clear description on the docs soon.

There are three way to get the ID in ci4:

$db = \Config\Database::connect();
$workModel = model('App\Models\WorkModel', true, $db);
$id = $workModel->insert($data);
        
echo $id;
echo '<br/>';
echo $workModel->insertID(); 
echo '<br/>';
echo $db->insertID();

To overcome this, I modified system/Model.php in the save() method---

$response = $this->insert($data, false);

// add after the insert() call 
$this->primaryKey = $this->db->insertID();

Now, in your models, you can just reference "$this->primaryKey" and it will give you the needed info, while maintaining the data modeling functionality.

I'm going to submit this over to the CI developers, hopefully it will be added in.

For CI4

$settings = new SettingsModel();
$settingsData = $settings->find(1);

<?php namespace App\Models;

use App\Models\BaseModel;

class SettingsModel extends BaseModel
{
    protected $table      = 'users';
    protected $primaryKey = 'id';
}

$settings->find(1); will return a single row. it will find the value provided as the $primaryKey.

hi guys in my case i use ci model to save data and my code is:

 $x=new X();
 $is_insert= $x->save(['name'=>'test','type'=>'ss']);
 if($is_insert)
     $inserted_id=$x->getInsertID()

I'm using mysql for my database then I ran this inside my seeder

$university = $this->db->table('universities')->insert([
    'name' => 'Harvard University'
]);
$faculty = $this->db->table('faculties')->insert([
    'name' => 'Arts & Sciences',
    'university' => $university->resultID
]);

Look at code line 6

$university->resultID

variable $university here is type object of CodeIgniter\Database\MySQLi\Result class

Corect me if I'm wrong or any room for improvements

In fact, what you did is correct. You did it in the best and easiest way and following the Codeigniter 4 Model usage guide.

You just missed: $id = $userModel->insertID;

Complete code using your example:

$data = [
        'username' => 'darth',
        'email'    => 'd.vader@theempire.com'
];

$userModel->save($data);

$id = $userModel->insertID;

That's it. You don't need all this code from the examples above nor calling database service or db builder if you're using codeigniter's models.

Tested on CodeIgniter 4.1.1 on 3/19/2021

I had the same problem but, unfortunately, the CI4 documentation doesn't help much. The solution using a builder woks, but it's a workaround the data modeling. I believe you want a pure model solution, otherwise you wouldn't be asking.

$data = [
        'username' => 'darth',
        'email'    => 'd.vader@theempire.com'
];

$id = $userModel->save($data);

Trying everything I could think of I decided to store the result of the save method to see if returned a boolean value to indicate if the saving was sucessful. Inspecting the variable I realized it returns exactly what I wanted: the lost insertID.

I believe CodeIgniter 4 is quite an easy and capable framework that does a decent job in shared hosts where other frameworks can be a little demanding if you're learning but lacks the same fantastic documentation and examples of CI3. Hopefully, that's only temporary.

By the way, you code works only if you are using the $userModel outside the model itself, for example, from a Controller. You need to create a model object like:

$userModel = New WhateverNameModel();
$data = [any data];
$userModel->save($data);

Alternatively, if you are programming a method inside the model itself (my favorite way), you should write

$this->save($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM