我正在尝试使用SyncWithoutDetaching()来更新数据透视表(active_pest),但我正在获取“调用数组成员函数active_pest()”错误消息。
这里的背景是我有8个表:产品,害虫,活性成分(即活性成分),作物,active_product,pest_product,crop_product和active_pest。我的表单收集有关所选(农用化学品)产品的信息 - 在该表格中,用户选择与该产品相关的害虫,活性成分和作物。提交后,我现有的代码将预期信息保存在products表中,并通过一组“belongsToMany”关系,active_product,pest_product和crop_product数据透视表也会正确更新。
对于任何给定的产品,通常有1或2个活动和3-8个害虫,它是我想要添加到active_pest数据透视表的那些id值。
我的代码是:
// ProductController
public function update(UpdateRequest $request)
{
$actives = $request->get('active');
$actives->active_pest()->SyncWithoutDetaching( $request->get('pest'));
...
}
// pest model
public function active_pest()
{
return $this->belongsToMany('App\Models\Pest', 'active_pest', 'active_id', 'pest_id');
}
有关此类错误消息的其他问题的答案表明active_pest()关系出现了问题 - 但在输入拼写错误后(active_pestr)我得到了相同的错误消息。无论如何,我不明白我做错了什么。
洞察力赞赏。谢谢,汤姆
$actives = $request->get('active');
只返回数组,所以你正在尝试这样的[1,2,3] - > active_pest()。
这正是它所说的。在数组上调用成员函数active_pest()。
你需要使用雄辩的实例来执行->active_pest()->SyncWithoutDetaching( $request->get('pest'));
所以你可以找到这样的实例:
$actives = Active::whereIn('col_name', $request->get('active'))->get();
这将返回您的实例集合,以保存每个需要使用foreach迭代的有害生物,如下所示:
foreach($actives as $active){
$active->active_pest()->SyncWithoutDetaching( $request->get('pest'));
}