Laravel 5设置模型事件到"清理"模型删除时的数据透视表

时间:2015-09-03 11:36:21

标签: php laravel laravel-5

我使用Laravel 5构建基于用户的应用程序。某些模型在我的应用中具有manyToMany关系,因此我使用数据透视表。

当我从系统中删除用户时,我使用这个简单的功能:

/**
 * Delete user.
 *
 * @param $id
 * @return mixed
 */
public function deleteUser($id)
{
    return $this->user->whereId($id)->delete();
}

但是,删除用户后,数据透视表中的行(例如role_user))不会被删除。

我已经阅读了laravel网站,我可以使用模型事件来清理"我的数据透视表,但我真的不确定如何实现它。

有人能指出我正确的方向吗?

修改

以下是我当前的模型设置:

namespace App\Models\User;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use App\Scopes\MultiTenantTrait;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, MultiTenantTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'user';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['cust_id', 'first_name', 'last_name', 'email', 'status', 'activation_code'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

    /**
     * Boot the model.
     *
     */
    public static function boot()
    {
        parent::boot();

        static::deleting(function($user)
        {
            $user->roles()->delete();
            $user->supervisors()->delete();
            $user->types()->delete();
            $user->rates()->delete();
            $user->miscs()->delete();
        });
    }
...

1 个答案:

答案 0 :(得分:2)

您可以为模型添加引导方法,如下所示:

public static function boot() {

    parent::boot();

    // This is a deleting event on the model
    static::deleting(function($model) {
        $model->... //Here your model is still available

        // You could add something like this
        DB::table('role_user')->where('user_id', $model->id)->delete();
    })
}

但您也可以在模型中扩展删除方法:

public function delete() {
    DB::table('role_user')->where('user_id', $this->id)->delete();
    parent::delete();
}