One to one relationship:
Suppose you have two tables users and addresses:
Users table:
id,name,email
Addresses table:
id,name, user_id
In the address table the user_id will come from the users table. Be careful about the naming convention.
Your Model name is User so table name is users so to get id from users table to addresses table you have to write according to the model name in the field of address like user_id.
So to declare one-to-one relationship:
Just think that user can have only one address. So, go to User model and write:
public function address(){
return $this->hasOne('App\Address');
}
here as this is one to one we are using singular function name which is address().
Store:
$user->address()-> save($address);
[Here, $user is finding the user by id, and $address is saving the requested address]
Show:
To show the address name
$user->address->name;
Update:
$address = Address::whereUserId(1)->first();
$address->name="Feni, Bangladesh";
$address->save();
Delete:
To delete address:
$user-> address()-> delete();
Thanks for reading.
Comments
Post a Comment