dsf8897 2017-08-12 16:11
浏览 33
已采纳

Laravel在播种表时设置增量id值

I'm trying to seed a MySql table using Laravel seeder class. The problem is that it is not assigning the id field (which is an incremental) value as I set. In the seeder class I got:

public function run()
{

    Patropi\Entidade::create([
        'id' => '0',
        'nome' => 'entidade 0',
        'cpfcnpj' => '12345678901'
    ]);

    Patropi\Fornecedor::create([
        'id' => '0',
        'prioridade' => '0'
    ]);
}

On the database, the Fornecedor table id is a foreign key which references the Entidade id, that's why I want to have the same Id on both. The problem is, when it inserts on Entidade it doesn't put it as id = 0 but instead it gives the value of the last incremental + 1. How to force laravel to insert 0 there instead? Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dsgfdgh14569 2017-08-12 16:56
    关注

    Storing NULL or 0 in the auto-incrementing field is one of the triggers to assign the next incremental value.

    From the MySQL docs:

    You can also explicitly assign 0 to the column to generate sequence numbers.

    If you want to disable this functionality, you can turn on the NO_AUTO_VALUE_ON_ZERO sql mode. This will change MySQL so that only assigning NULL will assign the next incremental value, and will allow you to store 0 in the field. From the docs:

    NO_AUTO_VALUE_ON_ZERO affects handling of AUTO_INCREMENT columns. Normally, you generate the next sequence number for the column by inserting either NULL or 0 into it. NO_AUTO_VALUE_ON_ZERO suppresses this behavior for 0 so that only NULL generates the next sequence number.

    This mode can be useful if 0 has been stored in a table's AUTO_INCREMENT column. (Storing 0 is not a recommended practice, by the way.)

    If you don't explicitly need the id to be 0, then I would not try to assign 0. If the id doesn't matter, then you can do this:

    public function run()
    {
        $entidade = Patropi\Entidade::create([
            'nome' => 'entidade 0',
            'cpfcnpj' => '12345678901'
        ]);
    
        Patropi\Fornecedor::create([
            'id' => $entidade->id,
            'prioridade' => '0'
        ]);
    }
    

    Or, if you have the Eloquent relationships setup:

    public function run()
    {
        $entidade = Patropi\Entidade::create([
            'nome' => 'entidade 0',
            'cpfcnpj' => '12345678901'
        ]);
    
        // assumes fornecedor() defines a hasone/hasmany relationship.
        $entidade->fornecedor()->create([
            'prioridade' => '0'
        ]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料