在播种机Laravel中自动创建自定义ID

92vpleto  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(155)

我想使用haruncpi/laravel-id-generator包定制id。我有2个数据将插入数据库。该程序是工作,但这些数据的id是重复的
下面是代码

class ArtisSeeder extends Seeder
{
    public function CustomId() 
    {
        $config = [
            'table' => 'artis', 
            'field' => 'kd_artis',
            'length' => 4, 
            'prefix' => 'A'
        ];

        return IdGenerator::generate($config);
    }

    public function run()
    {
        DB::table('artis')->insert([
            [
                'kd_artis' => $this->CustomId(),
                'nm_artis' => 'ROBERT DOWNEY',
                'jk' => 'PRIA',
                'bayaran' => 10000000000,
                'award' => 2,
                'negara' => 'AS',
            ], 
            [
                'kd_artis' => $this->CustomId(),
                'nm_artis' => 'ANGELINA JOLIE',
                'jk' => 'WANITA',
                'bayaran' => 700000000,
                'award' => 1,
                'negara' => 'AS',
            ], 
        ]);
    }
}

注意:kd_artis是id
那么如何使id不重复呢?

u1ehiz5o

u1ehiz5o1#

您可以通过Eloquent更轻松地保存和管理。在Seeder中这样使用:

Artis::insert([
    [
        'nm_artis' => 'ROBERT DOWNEY',
        'jk' => 'PRIA',
        'bayaran' => 10000000000,
        'award' => 2,
        'negara' => 'AS',
    ],
    [
        'nm_artis' => 'ANGELINA JOLIE',
        'jk' => 'WANITA',
        'bayaran' => 700000000,
        'award' => 1,
        'negara' => 'AS',
    ],
]);

别忘了在你的模型中加入这个。您可以根据自己的需要进行定制:

public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->kd_artis = IdGenerator::generate([
            'table' => $this->table,
            'field' => 'kd_artis',
            'length' => 4,
            'prefix' => 'A',
        ]);
    });
}

相关问题