我正在使用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();
});
}
...
您可以为您的模型添加一个启动方法,如下所示:
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();
})
}
但是你也可以在你的模型中扩展delete方法:
public function delete() {
DB::table('role_user')->where('user_id', $this->id)->delete();
parent::delete();
}