I’ve followed the Laravel docs, as well as a few tutorials, but I must be missing something as I’m getting a “Column not found” error on a foreign key. I’m hoping someone may be able to point it out.
I think the problem is that I don’t know how to “pass” the id for each User I create when trying to create a UserDetail record in the following:
factory(User::class, 3)
->create()
->each(function($u) {
$u->userdetail()->save(factory(UserDetail::class)->create());
});
The actual error is:
[Illuminate\Database\QueryException]
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'
(SQL: update `userdetails` set `user_id` = 1 where `id` = 0)
My users table has an auto-incrementing id field which is a foreign key to the user_id field in the userdetails table.
Here are the Models:
/*
* User Model
*/
class User extends Model {
// …
public function userdetail() {
# User has a User Detail
return $this->hasOne('Models\Users\UserDetail');
}
// …
}
/*
* UserDetail Model
*/
class UserDetail extends Model {
// …
public function user() {
# UserDetail belongs to User
return $this->belongsTo('Models\Users\User');
}
// …
}
Here are the Seeders:
/*
* UserTableSeeder
*/
class UserTableSeeder extends Seeder {
public function run() {
User::truncate();
UserDetail::truncate();
factory(User::class, 3)
->create()
->each(function($u) {
$u->userdetail()->save(factory(UserDetail::class)->create());
});
}
}
/*
* DatabaseSeeder
*/
class DatabaseSeeder extends Seeder {
DB::statement('SET FOREIGN_KEY_CHECKS = 0'); // disable foreign key constraints
Model::unguard();
$this->call('UserTableSeeder');
Model::reguard();
DB::statement('SET FOREIGN_KEY_CHECKS = 1'); // enable foreign key constraints
}
And, finally, the Model Factories:
$factory->define(User::class, function (Faker\Generator $faker) {
return [
'uname' => $faker->userName,
'pass' => bcrypt(str_random(8)),
'email' => $faker->email,
];
});
$factory->define(UserDetail::class, function (Faker\Generator $faker) {
return [
'street' => $faker->streetName,
'city' => $faker->city,
'state' => $faker->stateAbbr,
'zip' => $faker->postcode,
'phone' => $faker->phoneNumber,
];
});
Thanks for any guidance!
The problem is when you're assigning the relationship. You have to use the make()
method instead of the create()
as the create()
method will cause your model to be stored in the database while the make()
method only creates the instance then the save()
method will be the one to assign the required FK and store it in the database.
factory(User::class, 3)
->create()
->each(function($u) {
$u->userdetail()->save(factory(UserDetail::class)->make());
});