Laravel 根据枢轴额外字段从枢轴附加/分离模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33307937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Attach/Detach model from pivot depending on pivot extra field
提问by Cmorales
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 和 ManagementUnit 之间存在多对多关系。关联的实体每年都在变化,所以数据透视表是这样的:
council_id
management_unit_id
year
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 键可以出现多次,所以我不知道如何 attach() 或 detach() 模型。例如,如果我有这个:
council_id | management_unit_id | year
1 | 1 | 2010
1 | 1 | 2011
1 | 1 | 2012
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?
我将如何仅在 2011 年将 Council(1) 与 ManagementUnit(1) 分离?或者我如何将 2013 年的理事会(1)附加到 ManagementUnit(1)?
Working with Laravel 5.1
使用 Laravel 5.1
回答by Pawel Bieszczad
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);
回答by LipeTuga
In laravel 5.6 only worked with:
在 Laravel 5.6 中仅适用于:
$managementUnit = ManagementUnit::find(1);
$managementUnit->councils()->where('conuncils.id', 1)->wherePivot('year', 2011)->detach();