Laravel association model - also removing

Source of the problem

In the project, we often need to delete the data in a table, the table associated with it and there must be corresponding operations (delete or modify), Laravelit provides a very convenient method of operation

Solution

Now suppose we are doing a blog system, then there will be articles tables, user tables, and two tables is associated, if we need to delete the user's time and removes the corresponding data in the article, then Laravelthe:

// User Model
class User extends Eloquent
{
    // 与用户表关联的文章表
    public function posts()
    {
        return $this->hasMany('Post');
    }

    protected static function boot()
    {
        parent::boot();

        // 在删除用户时执行
        static::deleting(function($user) {
            // 删除与用户关联的文章
            $user->posts()->delete();
        });
    }
}

In this way, we delete the user when the corresponding article will be deleted, easy to operate a lot.

Of course, I think this can be extended, we can associate itself in the model corresponding data tables that do menu management when deleting a parent, it should be sub-classified delete, without the need for essay like me before [article some problems PHP attention when unlimited categories (not entirely correct to ensure that the code Oh) ], like so much trouble.

Guess you like

Origin www.cnblogs.com/Super-Lee/p/12622313.html