Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detach one instance from multiple in a laravel | Eloquent pivot table?

Pivot Table: 'bonus_circle' has the ability to have multiple items with the same circle_id and bonus_id. In other words There can be multiple of the same bonuses associated with the same circle. Using $circle->bonuses()->detach($id) removes ALL of the instances. I need it to only detach ONE instance. Does anyone know a work around for this?

like image 606
KernelCurry Avatar asked Jan 15 '14 22:01

KernelCurry


2 Answers

I had the same problem. Got around it using this.

DB::table($user->model()->getTable())
->where('role_id', 5)
->where('user_id', '=', $model->getKey())
->where('system_id', '=', 15)
->delete();
like image 163
gf1987 Avatar answered Oct 04 '22 07:10

gf1987


I searched for over a week for the answer to this. I can't use your code as an example because there's not quite enough there for me to go on, but I'll use my code to show you the answer I received from Kindari (thank you) in Laravel IRC chat.

I have users, roles, and accounts. A user can have one role on one or more accounts. My role_user_account table has role_id, user_id, account_id. I needed to remove a user's role where account_id = x But I found that detach() was removing ALL account roles for the user.

What didn't work:

$user->AccountRoles()->detach($role->id, array('account_id' => $account->id));

What does work:

$user->AccountRoles()->newPivotStatementForId($role->id)->whereAccountId($account->id)->delete();
like image 34
Christopher Raymond Avatar answered Oct 04 '22 09:10

Christopher Raymond