取决于枢轴额外字段,从枢轴获取Laravel附加/分离模型 [英] Laravel Attach/Detach model from pivot depending on pivot extra field

查看:31
本文介绍了取决于枢轴额外字段,从枢轴获取Laravel附加/分离模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与理事会和管理部门之间存在多对多关系.关联的实体每年都在变化,因此数据透视表如下所示:

I have a Many To Many relationship between Council and ManagementUnit. The associated entities change from year to year, so the pivot table is like this:

council_id
management_unit_id
year

我的问题是,同一组合的Council_id + management_unit_id组合键可能会出现几次,所以我不知道如何对模型进行attach()或detach().例如,如果我有这个:

My problem is that the same combined council_id + management_unit_id keys can appear several times, so I don't know how to attach() or detach() the models. For example, if I had this:

council_id | management_unit_id | year
1          | 1                  | 2010
1          | 1                  | 2011
1          | 1                  | 2012

我仅在2011年如何将Council(1)与ManagementUnit(1)分离?还是在2013年将Council(1)附加到ManagementUnit(1)上?

how would I detach Council(1) from ManagementUnit(1) only for 2011? or how would I attach a Council(1) to ManagementUnit(1) for 2013?

使用Laravel 5.1

Working with Laravel 5.1

推荐答案

不确定关系的设置方式,因此您可能需要稍作调整.但请尝试一下:

Not sure how your relations are set so you might have to adjust this a little. but give it a try:

$managementUnit = ManagementUnit::find(1);
$managementUnit->councils()->where('id', 1)->wherePivot('year', 2011)->detach(1);

这篇关于取决于枢轴额外字段,从枢轴获取Laravel附加/分离模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆