dongxian3574 2015-08-12 16:55
浏览 39

防止播种唯一的密钥违规

I have a unique constraint in my database for two columns.

$table->unique(array("table_a_id", "table_b_id"));

Now I use Faker in a seeder class to fill in this pivot table:

$tableAIds = TableA::all()->lists("id")->toArray();
$tableBIds = TableB::all()->lists("id")->toArray();

foreach(range(1, 20) as $index) {
    $tableAId = $faker->randomElement($tableAIds);
    $tableBId = $faker->randomElement($tableBIds);

    DB::table("table_a_table_b_pivot")->insert([
        "table_a_id" => $tableAId,
        "table_b_id" => $tableBId
    ]);
}

However this creates duplicates and the seeding fails due to SQL error.

How do I make sure I don't try to insert duplicates?

  • 写回答

3条回答 默认 最新

  • dongpao9165 2015-08-12 17:12
    关注

    Instead of using faker, use the collection's random method:

    $tableAIds = TableA::all()->lists('id')->random(20);
    $tableBIds = TableB::all()->lists('id')->random(20);
    
    foreach(range(0, 19) as $index) {
        DB::table("table_a_table_b_pivot")->insert([
            "table_a_id" => $tableAIds[$index],
            "table_b_id" => $tableBIds[$index],
        ]);
    }
    

    Adjust this according to your needs.

    For example, this might be what you really want:

    $tableAIds = TableA::all()->lists('id');
    $tableBIds = TableB::all()->lists('id');
    
    foreach ($tableAIds->random(5) as $tableAId) {
        foreach ($tableBIds->random(2) as $tableBId) {
            DB::table("table_a_table_b_pivot")->insert([
                "table_a_id" => $tableAId,
                "table_b_id" => $tableBId,
            ]);
        }
    }
    

    Whatever it is, play with it yourself. No need for faker here.

    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加