如何在Laravel写播种机

时间:2017-08-15 06:36:42

标签: php laravel laravel-5 php-7 laravel-seeding

我有表格可标记,它是多对多多元关系(标签和帖子)的表格:

taggable_id - id of Post
tag_id - id of Tag
taggable type - location of post model (default value"App/Models/Posts/Post")
is_search_term - boolen (0 or 1)

如何创建每次为关系创建相同记录的播种机?

1 个答案:

答案 0 :(得分:2)

如果db_id设置为主键,则db_id将自动创建,taggable_id将从Tag模型中获取值。

你可以尝试这样的事情;

$factory->define(App\Tag::class, function (Faker\Generator $faker) {
    return [
        'taggable_id' => random_int(\DB::table('posts')->min('id'), \DB::table('posts')->max('id')),
        'is_search_term'=>$faker->numberBetween(0,1),
'taggable_type'=>$faker->sentence(2),

    ];
});