Created
December 19, 2013 21:17
-
-
Save angelmartz/8046409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ugust 23rd 2013 | |
| USING LARAVEL 4′S MODEL EVENTS TO CASCADE DELETION | |
| Cascading deletion in Laravel 4 can be accomplished setting up FOREIGN KEY‘s and adding an ->onDelete('cascade') in your Schema. | |
| Read on for an alternative way to cascade a deletion using Events. | |
| Assume you have a Model called Author which has many Books. | |
| class Author extends Eloquent { | |
| public function books() | |
| { | |
| return $this->hasMany('books'); | |
| } | |
| } | |
| If you delete an Author instance, you probably want to delete all associated Books as well. This is easily done Using Laravel 4′s Model Events. | |
| class Author extends Eloquent { | |
| public static function boot() | |
| { | |
| parent::boot(); | |
| static::deleted(function($author) | |
| { | |
| Book::destroy($author->books()->lists('id')); | |
| }); | |
| } | |
| public function books() | |
| { | |
| return $this->hasMany('books'); | |
| } | |
| } | |
| The Illuminate\Database\Eloquent\Collection()->lists() method is very useful in this context, as it returns an array of the specified attribute from the Collection. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment