Laravel Classroom image

Prashant  Nigam / Student / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2 | 3 | 4 | 5 | 6|Last
Lessons:-Eloquent ORM

11.3 Inserting Related Models
When we are inserting related models, we can set the user_id or hat_id foreign key ourselves,
but thats not very pretty. Why not pass the object instead?1 <?php
2
3 $hat = Hat::find(1);
4 $user = User::find(1);
5 $user->hats()->insert($hat);
That looks a lot better! It’s like handing objects to each other and is much cleaner than dealing
with those integer foreign keys directly.
With has_many() relationships you can pass an array of field-value pairs to the save() method
to insert or update related models. For example:
1 <?php
2
3 $hat = array(
4 'name' => 'Dennis',
5 'style' => 'Fedora'
6 );
7
8 $user = User::find(1);
9
10 $user->hats()->save($hat);
Clean!
When we are creating a new related item with a many-to-many relationship, if we use the
insert() method Eloquent will not only create the new object, but also update the pivot table
with the new entry. For example :
1 <?php
2
3 $hat = array(
4 'name' => 'Dennis',
5 'style' => 'Fedora'
6 );
7
8 $user = User::find(1);
9
10 $user->hats()->insert($hat);
But what if the objects already exist, and we just want to create the relationship between them?
We can do this easily with the attach() method by passing the $id (or the object) of the object
to be related. Let’s see the code.
1 <?php
2
3 $user->hats()->attach($hat_id);The pivot will have been updated for you!
Next is a method that I myself have only recently become aware of. I will assume it arrived with
Eloquent in 3.1. We can use the sync() method with an array of ids and once the method has
executed only the id’s in the array will be in the pivot table. Very handy! Here’s a code snippet.
1 <?php
2
3 $user->hats()->sync(array(4, 7, 8));

 

 

 
 
 

Prashant  Nigam

Skills    Laravel

Qualifications :-
Location :-,,,
Description:-
Explore
 

  Students (0)