Php 更新laravel中的透视表
我有Php 更新laravel中的透视表,php,laravel,Php,Laravel,我有服务和项目表格。我将数据透视表作为服务项目。我能够将数据存储到数据透视表中,但是我无法获得更新数据透视表的正确语法。我的代码在尝试更新现有数据时存储新数据 PS:虽然我的代码可以编辑客户的姓名,但不能编辑客户先前购买的物品 我希望能够更新商品id和数量 服务项目-枢轴 service_id item_id qty 控制器 public function store(Request $request) { $service = new Service(array(
服务
和项目
表格。我将数据透视表作为服务项目
。我能够将数据存储到数据透视表中,但是我无法获得更新数据透视表的正确语法。我的代码在尝试更新现有数据时存储新数据
PS:虽然我的代码可以编辑客户的姓名,但不能编辑客户先前购买的物品
我希望能够更新商品id和数量
服务项目-枢轴
service_id
item_id
qty
控制器
public function store(Request $request)
{
$service = new Service(array(
'id' => $service_no,
));
$service->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->attach($selectedItems);
}
public function update($id, Request $request)
{
$service = Service::findOrFail($id);
$service->clients->name = $request->get('name');
$service->clients->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->attach($selectedItems);
}
好的,经过研究,我能够使用
updateExistingPivot
public function update($id, Request $request)
{
$service = Service::findOrFail($id);
$service->clients->name = $request->get('name');
$service->clients->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->updateExistingPivot($item_id, ['quantity' => selectedItems], false);
}
好的,经过研究,我能够使用
updateExistingPivot
public function update($id, Request $request)
{
$service = Service::findOrFail($id);
$service->clients->name = $request->get('name');
$service->clients->save();
$selectedItems = [];
foreach($request->get('item_id') as $key => $id) {
$selectedItems[$id] = ['qty' => $request->get('quantity')[$key]];
}
$service->items()->updateExistingPivot($item_id, ['quantity' => selectedItems], false);
}
可能我没有正确理解,但是谁是$service\u no from$service=new service(数组('id'=>$service\u no,@Radu),我没有这个问题(将服务存储到我的数据库中)。现在,
$service\u no
是我正在创建的服务的id,我使用算法将其生成到变量$service\u no
中。我没有包括算法,但它可以工作。我认为问题在于外键。尤其是在透视表中的service\u id foreign中。检查,您使用的更新服务正确吗?@LearnLaravel谢谢,请看本教程是否有帮助:我相信,每个单独的应用程序在每个数据透视中都应该有完全相同的列名。对于任何关系,我总是有相关id
和条目id
。可能我没有正确理解,但谁是$service\u no from$service=new service(数组)中的$service('id'=>$service_no,@Radu,我对此没有问题(将服务存储到我的数据库中)。现在,$service\u no
是我正在创建的服务的id,我使用算法将其生成到变量$service\u no
中。我没有包括算法,但它可以工作。我认为问题在于外键。尤其是在透视表中的service\u id foreign中。检查,您使用的更新服务正确吗?@LearnLaravel谢谢你,请看看本教程是否有帮助:我相信,每个单独的应用程序在每个pivot中都应该有完全相同的列名。对于任何关系,我总是有相关id
和条目id
。