Laravel 8 中出现 "Method Illuminate\Database\Eloquent\Collection::attach does not exist" 错误

5
我尝试为产品添加分类。我想使用项和分类之间的一对表来实现。我在我的控制器中编写了一个函数将其发送到数据库。然而,在我想要发送它时,我遇到了以下错误,我不知道该如何修复它。Method Illuminate\Database\Eloquent\Collection::attach不存在。
控制器:
public function store(ItemsValidatorRequest $request)
    {
        if ($files = $request->image) {
            $destinationPath = 'images';
            $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
            $files->move($destinationPath, $profileImage);
        }
        else {
            return redirect()->back()->with('warning', 'Mislukt');
        }
        $user = Auth::user()->id;

        Item::create([
            'user_id' => $user,
            'item_title' => $request->titel,
            'item_img' => $profileImage,
            'item_description' => $request->beschrijving,
            'item_price' => $request->prijs,
            'item_slug' => $this->slugify($request->titel)
        ]);

        $items = Item::latest()->get();
   

     // line where it goes wrong
        $items->each->categories()->attach($request->categories);

        return redirect()
            ->route('admin.items.index')
            ->with('success', 'Het item is toegevoegd aan je verlanglijst');
    }

我的模型:

public function categories()
    {
        return $this->belongsToMany('App\Models\Category');
    }
1个回答

2

Laravel的高阶函数调用只需要一个方法调用,而不是多个。因此,如果您在Item类上创建一个助手方法,它将解决您的问题。

class Item {
    public function attachCategories($categories) {
        $this->categories()->attach($categories);
    }
}

这将使得可以这样分配类别。
$items->each->attachCategories($request->categories);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接