Laravel - Seeding Relationships

前端 未结 6 518
感情败类
感情败类 2020-12-07 14:58

In Laravel, database seeding is generally accomplished through Model factories. So you define a blueprint for your Model using Faker data, and say how many instances you ne

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-07 15:30

    I want to share the approach i've taken for insert many posts to many users:`

    factory(App\User::class, 50)->create() 
                    ->each( 
                        function ($u) {
                            factory(App\Post::class, 10)->create()
                                    ->each(
                                        function($p) use (&$u) { 
                                            $u->posts()->save($p)->make();
                                        }
                                    );
                        }
                    );
    

    `

    This workaround worked for me after being all day long looking for a way to seed the relationship

提交回复
热议问题