简体   繁体   English

如何在Laravel中从多个实例中分离一个实例| 雄辩的数据透视表?

[英]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. 数据透视表:“ bonus_circle”具有多个具有相同circle_id和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. 使用$ circle-> bonuses()-> detach($ id)删除所有实例。 I need it to only detach ONE instance. 我需要它仅分离一个实例。 Does anyone know a work around for this? 有谁知道解决此问题的方法?

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. 我无法使用您的代码作为示例,因为那里没有足够的代码供我继续进行,但是我将使用我的代码向您展示我在Laravel IRC聊天中从Kindari(谢谢)收到的答案。

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. 我的role_user_account表具有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. 我需要删除account_id = x的用户角色,但是我发现detach()删除了该用户的所有帐户角色。

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();

Raw Query现在可以使用,但是如果有人可以回答这个问题,我将不胜感激。

DB::delete('DELETE FROM bonus_circle WHERE bonus_id = ? AND circle_id = ? LIMIT 1',[$bonus->id, $circle->id]);

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM