CodeIgniter Forums
Entity Insert Issue - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: Entity Insert Issue (/showthread.php?tid=90890)



Entity Insert Issue - CodeXpedite - 05-18-2024

Greetings to all. I’m working on optimizing my code and have opted to implement the Entity class. However, I’m dealing with a ‘genres’ table and a ‘books_genres’ table. Below is the code I’m currently using:


PHP Code:
namespace Library\Entities;

use 
CodeIgniter\Entity\Entity;

class 
BookEntity extends Entity
{
    protected $datamap = [];
    protected $dates  = ['publication_date''created_at''updated_at''deleted_at'];
    protected $casts  = [
        'genres' => '?array'
    ];

    public function getGenres()
    {
        $bookGenresMdl = new \Library\Models\BooksGenresModel();
        $genres $bookGenresMdl->where('book_id'$this->id)->findAll();
        $genresList = [];
        foreach ($genres as $genre) {
            $genresList[] = $genre['genre_id'];
        }
        return $genresList;
    }

    public function setGenres($genres)
    {
        if ($this->id) {
            $genres unserialize($genres);
            $bookGenresMdl = new \Library\Models\BooksGenresModel();

            $bookGenresMdl->where('book_id'$this->id)->delete();

            foreach ($genres as $genre) {
                $bookGenresMdl->insert([
                    'book_id' => $this->id,
                    'genre_id' => $genre
                
]);
            }
        }
        return $this;
    }



When updating existing records, the process works fine. However, when attempting to add a new record, although the task completes, the ID is not generated in time, leading to a failure. Is there a solution to this issue, or must I generate the ID within the model or controller?


RE: Entity Insert Issue - warcooft - 05-18-2024

The id should be generated automatically but depending on how you create the file migration, this behavior depends on the file migration you create.
and then in your model set $useAutoIncrement to true as follows:
PHP Code:
protected $useAutoIncrement true