How do you define foreign keys in a model factory. For example if I have a organisations table which has a foreign key to the countries table, in my model factory I'm having to define a dummy value for the country id as follows:
$factory->define(App\Organisation::class, function ($faker) {
return [
'name' => $faker->company,
'country_id' => 197,
];
});
In my organisations table seeder class I am doing the following but the faker object isn't present - do I need to create a new faker object in my seeder 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();
}
}
Whats the best way to define the foreign keys when defining model factories? Is it possible to omit the country_id from the model factory and add it in the seeder class instead - from the documention it seems you can only override an existing value defined in the model factory but you cant add a new value via the seeder class - correct me if i'm wrong?
organization
will have one different country and it will never use an existing one, right? – Davison