Welcome Guest, Not a member yet? Register   Sign In
Entity Insert Issue
#1

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?
Reply
#2

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
@xxxx[{::::::::::::::::::::::::::::::::>
Reply




Theme © iAndrew 2016 - Forum software by © MyBB