doudou8893 2016-03-19 18:18
浏览 32
已采纳

创建父级时创建模型(例如,在创建用户时创建5个帖子)

If a User has many posts, and a post belongs to user, it's simple to do:

$factory->define(App\Post::class, function ($faker) {
    return [
        'title' => $faker->title,
        'content' => $faker->paragraph,
        'user_id' => function () {

            // Creates a User for every Post
            return factory(App\User::class)->create()->id;
        }
    ];
});

How do I accomplish the opposite? Instead, creating say 5 posts when a user is created and associating that post to the newly created user?

~Edit I am using laravel 5.2, and I've declared my model relationships in my models, so I now have:

$user = factory(App\User::class)->create();
$posts = factory(App\Post::class, 3)->make();
$user->posts()->saveMany($posts);

// Great, now I have a User and 3 Posts associated with that user. 


// However, now, I want let's say, 5 votes per post.
// I can't call $posts->votes(), so I iterate

foreach ($posts as $post) { 
    $votes = factory(App\Votes::class, 5)->make();
    $post->votes()->saveMany($votes);
}

Then any other relation to votes, etc would just be nested in the foreach.

  • 写回答

2条回答 默认 最新

  • duanan1228 2016-03-19 18:28
    关注
    $factory->define(App\User::class, function ($faker) {
        return [
            'name' => $faker->name,
            'email' => $faker->email
        ];
    });
    
    $factory->define(App\Post::class, function ($faker) {
        return [
            'title' => $faker->title,
            'content' => $faker->paragraph
        ];
    });
    
    
    $user = factory(User::class)->create();
    
    $post = factory(User::class)->create();
    

    $user->posts()->associate($post);

    Create 5 fakers in $posts

    $posts = factory(App\Post::class, 3)->make();
    $user->posts()->saveMany($posts);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址