ONE TO MANY RELATIONSHIP
In one to many
relationship tables are same like one to one but add some more values in both
tables
In controller indicate which one is shown shown in json
file
public function hasmanyjson(){
$user = User::with('phone_om')->whereId(2)->first();
return Response::json($user);
}
Then to create hasMany function in User model
public function phone_om(){
return $this->hasMany(Phone::class);
}
Now call the public function name in route
Route::get('/hasmanyjson', [Usercontroller::class, 'hasmanyjson']);
To see the output view in json format
ONE TO MANY INVERSE
One
to many inverse (BelongsTo) is opposite of one to many its like table 2
to table 1 calling method
We create a public function in controller to
mentioned which one is join id for table then show it in json formate
public function hasmany2(){
$phone = Phone::with('user')->whereId(3)->first();
return Response::json($phone);
}
In Phone model using belongsTo function to inverse
the function
public function user(){
return $this->belongsTo(User::class);
}
Call the controller public function in route
Route::get('/hasmany2', [Usercontroller::class, 'hasmany2']);
Now we will see output file in Jason formate
ADD VALUES IN PHONES TABLE
Add
extra values in phone table on controller public function creating new object
in class using saveMany function
public function addphno(){
$user = User::find(3);
$phone2 = new Phone;
$phone2->phone = "444444444";
$phone3 = new Phone;
$phone3->phone = "333333333";
$user->phone_om()->saveMany([$phone2, $phone3]);
return 'created!';
}
Call that function in route
Route::get('/addphno', [Usercontroller::class, 'addphno']);
See word created in web page, this is hint we create the values are updated in phones table
Now to check the database for see the changes
CHANGE FOREIGN KEY
We
see how to change the foreign key in controller
Firstly we will set which id key was changed mention
that key in find function than with help of associate function to change the
foreign key
public function chan_fk(){
$phone = Phone::find(3);
$user = User::find(1);
$phone->user()->associate($user)->save();
return 'Changed';
}
Now call that function in route
Route::get('/chan_fk', [Usercontroller::class, 'chan_fk']);
To see the web page your hint word was displayed on the page
To check the database for values are updated
Comments