当我删除模型时,Laravel模型关系产生错误的sql


Laravel model relationship producing wrong sql when I delete a model

我正在构建一个具有用户和用户角色的应用程序。一个用户可以拥有多个角色。

我有3个表设置:

    用户
  • role_user

在我的user模型中,我有这个:

...
/**
 * Boot the model.
 *
 */
public static function boot()
{
    parent::boot();
    static::deleting(function($user)
    {
        $user->roles()->delete();
    });
}
/**
 * The roles that belong to the user.
 *
 * @return Object
 */
public function roles()
{
    return $this->belongsToMany('SimplyTimesheets'Models'User'Role')->withTimestamps();
}
...

当我删除一个用户时,我希望它也从role_user表中删除相关的行。

我的删除方法是这样的:

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

但是,这会生成以下SQL:

delete `role` from `role` inner join `role_user` on `role`.`id` = `role_user`.`role_id` where `role`.`cust_id` = ? and `role_user`.`user_id` = ?

为什么试图从role表中删除行,而不是从role_user表中删除行?

我错过了什么?

谢谢。

使用detach方法,而不是delete方法:

public static function boot()
{
    parent::boot();
    static::deleting(function($user)
    {
        $user->roles()->detach();
    });
}