06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Eloquent: Relationships 599<br />

If you need to save multiple related models, you may use the saveMany method:<br />

1 $post = App\Post::find(1);<br />

2<br />

3 $post->comments()->saveMany([<br />

4 new App\Comment(['message' => 'A new comment.']),<br />

5 new App\Comment(['message' => 'Another comment.']),<br />

6 ]);<br />

Save & Many To Many Relationships<br />

When working with a many-to-many relationship, the save method accepts an array of additional<br />

intermediate table attributes as its second argument:<br />

1 App\User::find(1)->roles()->save($role, ['expires' => $expires]);<br />

The Create Method<br />

In addition to the save and saveMany methods, you may also use the create method, which accepts<br />

an array of attributes, creates a model, and inserts it into the database. Again, the difference between<br />

save and create is that save accepts a full Eloquent model instance while create accepts a plain<br />

PHP array:<br />

1 $post = App\Post::find(1);<br />

2<br />

3 $comment = $post->comments()->create([<br />

4 'message' => 'A new comment.',<br />

5 ]);<br />

Before using the create method, be sure to review the documentation on attribute mass assignment.<br />

Updating “Belongs To” Relationships<br />

When updating a belongsTo relationship, you may use the associate method. This method will set<br />

the foreign key on the child model:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!