2017-04-25 58 views
1

我想使用faker播種我的數據庫,但是我有一些異常元素的問題。我有一個用戶,但我不知道它的ID。我希望所有帖子都有它的ID。
這是我如何做到這一點:指定一個值來創建隨機元素

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]); 
} 

這是我的帖子廠:

$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), 
    ]; 
}); 

一個db:seed後,這是我的錯誤(用戶和類別以及人口):

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)) 

這裏的用戶ID是1或應該是9.爲什麼?

+0

看起來這樣每次都會創建一個新用戶,但是您正在調用表中的第一個用戶。是這種情況,還是你刷新你的遷移? – Naltroc

+0

我刪除用戶和類別un phpmyadmin。有沒有更好的方式來截斷與關係表? – Wizix

+0

使用'php artisan migrate:refresh --seed'將完全回滾並遷移數據庫以及填充播種器文件。只要你在數據庫中沒有有價值的數據,這就很好。 一般而言,使用遷移來管理數據庫是一種很好的做法,儘管我已經發現自己會每隔一段時間手動刪除一次。 – Naltroc

回答

0

我推薦給種子您的數據庫如下:

  1. 爲了避免手動刪除數據庫條目,與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]); 
    } 
    

現在每次運行工匠命令db:seed ,你截斷你的用戶表,然後你用新的數據填充你的數據庫,因此你可以獲取單個用戶,也可以獲取正確的用戶first()方法。

+0

因爲外鍵不能使用這個,但是這個解決方案:http://stackoverflow.com/questions/31192207/laravel-5-1-migration-and-seeding-cannot-truncate-a-table-referenced-in -a-foreig正在工作。那謝謝啦! – Wizix