dtgv52982 2017-04-25 20:11
浏览 5

指定一个值以创建随机元素

I'm trying to seed my database with faker, but I have some issues with a foreign element. I have one and only user and I don't know its id. I want all the posts to have its id.
This is how I did this :

public function run()
{
    factory(App\User::class)->create();
    factory(App\Category::class, 3)->create();

    $user = \App\User::first();

    factory(App\Post::class, 10)->create(['author_id' => $user->id]);
}

And this is my post factory :

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'title' => $faker->unique()->sentence(5),
        'subtitle' => $faker->optional()->sentence(10),
        'markdown' => $faker->text(500),
        'draft' => $faker->boolean(),
        'category_id' => $faker->numberBetween(1, 6),
    ];
});

After a db:seed, this is the error I get (users and categories are well populated) :

  SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`laman`.`posts`, CO
  NSTRAINT `posts_author_id_foreign` FOREIGN KEY (`author_id`) REFERENCES `users` (`id`)) (SQL: insert into `posts` (`title`, `slug`, `subtit
  le`, `markdown`, `draft`, `category_id`, `author_id`, `html`, `published_at`, `updated_at`, `created_at`) values (title.,
   slug, , markdown, 0, 6, 1, html, 2017-04-25 20:08:34, 2017-04-25 20:08:34, 2017-04-25
  20:08:34))

Here the user id is 1 or it should be 9. Why?

  • 写回答

1条回答 默认 最新

  • duanchangnie7996 2017-04-25 21:40
    关注

    i recommend to seed your DB as follows:

    1. To avoid manually deleting db entries, populate your seeder with DB::table('YourDBTable')->truncate(); :

      public function run()
      {
          DB::table('user')->truncate();
          DB::table('posts')->truncate();
      
          factory(App\User::class)->create();
          factory(App\Category::class, 3)->create(); 
      
          $user = \App\User::first();
      
          factory(App\Post::class, 10)->create(['author_id' => $user->id]);
      }
      

    Now everytime you run artisan command db:seed, you truncate your users table after which you are populating your db with fresh data and thus you are able to fetch the single one user, and the right one too, with the first() method.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测