jeudi 3 septembre 2015

Laravel model relationship producing wrong sql when I delete a model

I am building an app that has users and user roles. A user can have many roles.

I have 3 tables setup:

  • user
  • role
  • role_user

In my user model I have this:

...

/**
 * 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();
}

...

When I delete a user, I want it to delete the associated row(s) from role_user table also.

My delete method looks like this:

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

However, this results in the following SQL being generated:

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

Why is it trying to delete the row from role table and not from role_user?

What am I missing?

Thanks.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1QbnMSt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire