Initial Value Sequences Postgresql - Laravel 5.1

Asked

Viewed 324 times

4

Good morning, I am running some tests on my application, but I have the following problem: After the migrate and the db:seed, whenever I will enter some record by applying a duplicated primary key error. I have seen that this error is due to the increment continue to 1 even after entering data with db:seed. Would there be some way for me to set this value manually automatically, without having to go from table to table and changing?

Seed:

 public function run()
    {
        Model::unguard();

        App\Models\Admin\Profissao::create(['id'                       => '1', 
            'titulo'                => 'Engenheiro(a)',
        ]);

        App\Models\Admin\Profissao::create(['id'                       => '2', 
            'titulo'                => 'Tecnólogo(a)',
        ]);

        Model::reguard();
    }

Migration:

public function up()
{
    Schema::create('profissoes', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('titulo', 16);
        $table->longText('descricao')->nullable();
        $table->timestamps();
    });
}
  • ideal is you leave the table blank and perform the Seed, already tried it?

  • Post your Seed and your Migration. Are you setting the column in the database to Serial? Your Seed is setting values for the ID column manually?

  • What do you mean? What I do is I run migrate to create the tables, so it’s all going to be blank, right? And then I run Seed, but Seed doesn’t change the increment there in the sequences.

  • Posted @Marcoauréliodeleu

  • 1

    Remove the id column specification from your seeder and make sure the problem goes away. That is, just put the title column in the seeder.

  • Okay, I’ll see here.

  • That’s right @Marcoauréliodeleu. I didn’t really think it could be this... Thank you so much!

Show 2 more comments

1 answer

4


The problem is in your Seeder:

 public function run()
 {
    Model::unguard();
    App\Models\Admin\Profissao::create(['titulo' => 'Engenheiro(a)']);
    App\Models\Admin\Profissao::create(['titulo' => 'Tecnólogo(a)']);
    Model::reguard();
}

This way, you will not specify the ID column value manually.

The problem is that, unlike Mysql, Postgresql uses sequences. These sequences are separate structures from the table. In Mysql, when inserting a record with the ID column set, the table will automatically move to the next value when auto-incrementing. In Postgresql, the structure sequence did not know that the value was entered because you did not use the sequence.

Since you do not specify the value, Laravel will use the sequence for you and it will automatically be incremented.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.