Monday, March 20, 2017

Default foreign key in laravel for relationship pointing wrongly

Laravel asks for users_id instead of user_id I have two table Users (id, name, email..) and Country (id, user_id, country..).

User model

public function countries(){
   return $this->hasOne('App\User');
}

Country model

public function users(){
   return $this->belongsTo('App\User');
}

Controller

$user = $user = User::find(1);
$country = new Country();
$country->country = 'TN';
$country->users()->associate($user);
$country->save();

Error

Unknown column 'users_id' in 'field list' (SQL: insert into `countries` (`country`, `users_id`, `updated_at`, `created_at`)

I am confused, I do not know whether I am right or wrong. Can someone Explain me why its asking for users_id.



via fernandus

Advertisement