简体   繁体   中英

How to define belongsTo relationship in Laravel factory?

I have a Post, User and Country model.

A Post belongsTo as User. A User belongsTo a Country.

Is there any way to call the User and Country factory from after the post factory?

Sort of like


factory(Post::class,10)
    ->create()
    ->each(function($post){
       $post
            ->user()
            ->save(
                  factory(User::class)
                      ->create(['some_column' => 'with_some_custom_data'])        
                      ->each(function($user){
                          $user
                              ->country()
                              ->save(
                                  factory(Country::class)
                                  ->create(['name' => 'some_custom_name']);
                               );
                        });
                 );
            }
      });

->save() does not work with belongsTo .

using Larave 7.2

Solved.

needed to use relation_column_id as factory.

so

// post factory 

[
 ... 
 'user_id' => factory(User)->create(),
]

// user factory 
[
  ...
  'country_id' => factory(Country)->create()
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM