Laravel 5.1 foreign keys in a factory model

How do you define foreign keys in a factory model. For example, if I have an organization table that has a foreign key for the country table, in my factory model I need to define a dummy value for the country identifier as follows:

$factory->define(App\Organisation::class, function ($faker) { return [ 'name' => $faker->company, 'country_id' => 197, ]; }); 

In my organizational class seeder classes, I do the following, but there is no faker object - do I need to create a new faker object in my seeders class?

 use Illuminate\Database\Seeder; class OrganisationsTableSeeder extends Seeder { public function run() { $countryIds = Country::lists('id')->all(); factory('App\Organisation', 3)->create([ // override factory default 'country_id' => $faker->randomElement[$countryIds], ]); } } 

Database Seeder Class

 class DatabaseSeeder extends Seeder { public function run() { Model::unguard(); $this->call('CountriesTableSeeder'); $this->call('OrganisationsTableSeeder'); Model::reguard(); } } 

What is the best way to define foreign keys when defining model factories? Is it possible to omit country_id from the factory model and add it to the seeder class instead - from the document, it looks like you can override the existing value defined in the factory model, but you cannot add a new value through the seeder class - correct me if I'm wrong?

+7
foreign-keys faker
source share
2 answers

Maybe I was a little late for this question, but I had the same problem, this fixed it for me. You should be able to do

 $factory->define(App\Organisation::class, function ($faker) { return [ 'name' => $faker->company, 'country_id' => factory(App\Country::class)->create()->id, ]; }); 

and then in your seed you just need to call

 factory(App\Organisation::class, 5)->create(); 

and this will create countries for you.

+2
source share

What the Laravel, Otwell, Stauffer et.al. team offers is as follows.

Testing> Adding Relationships to Models

Adding Relationships to Your Models

ModelFactory.php

 $factory->define(App\Organisation::class, function ($faker) { return [ 'name' => $faker->company, 'country_id' => 197, ]; }); $factory->define(App\Country::class, function ($faker) { return [ 'name' => $faker->country, ]; }); 

Seeder

 $organisations = factory('App\Organisation', 3) ->create() ->each(function($$organisation) { $organisation->relatedItems()->save(factory('App\Country')->make()); }); 
0
source share

All Articles