我在morphToMany关系中具有以下2个模型:Company和Tag
public function tags(){
return $this->morphToMany(Tag::class, 'taggable');
}
public function companies(){
return $this->morphedByMany(Company::class, 'taggable');
}
并且我有以下工作措施将1个标签保存到1个公司:
public function addTag($request){
$company = Company::find($request->company_id);
$company->tags()->syncWithoutDetaching($request->tag_id);
return response()->json($company->tags, 201);
}
现在我正在尝试对许多公司和许多标签执行相同的操作,但是它不起作用。我已经尝试过“ syncWithoutDetaching”,“ saveMany”,并传入整数或字符串数组,但我一直收到此错误:
BadMethodCallException: Method Illuminate\Database\Eloquent\Collection::tags does not exist. in file /home/vagrant/.../vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php on line 100
这是我正在使用的功能:
public function multiCompanyAddTags($request){
$tags = $this->createManyRecords('App\AppSections\CRM\Models\Tag', $request->new_tags);
$tagIDs = $tags->map(function ($item, $key) { return $item->id;
});
foreach ($request->companies as $key=>$id)
{
$company = Company::with(['notes','tags','contacts','tasks'])->find($id);
$company->tags()->syncWithoutDetaching($tagIDs);
return response()->json($company, 201);
}
}
答案 0 :(得分:0)
有人指出我的答案:在循环中调用$ company = Company :: with ...时,该调用返回集合而不是公司。
然后我需要调用集合的第一项来访问公司,就像这样:
$company[0]->tags()->syncWithoutDetaching($tagIDs);