尝试将数据发送到 Laravel 8 中的两个表时集合不存在

Collection doesn't exist while trying to send data to two tables in Laravel 8

我正在尝试为产品添加类别。我想用项目和类别之间的几个表来做到这一点。我在我的控制器中创建了一个函数来将它发送到数据库。但是,当我要发送时,出现以下错误,我不知道是否可以修复它。

Method Illuminate\Database\Eloquent\Collection::does not exist

控制器

public function store(ItemsValidatorRequest $request)
{
    $items_id = Item::select('items_id')->latest()->get();
    $item = Item::find($items_id);
    $item->categories()->attach($request->categories);
}

型号

public function categories()
{
    return $this->BelongsToMany('App\Models\Category');
}

$items_id 将是一个 id 数组,因此 Item::find($items_id) 将 return collection 个项目,每个项目都有类别。所以尝试使用 each higher order messages:

$items_id = Item::select('items_id')->latest()->get();
$items = Item::find($items_id);
$items->each->categories()->attach($request->categories);

或者简单地说:

$items = Item::latest()->get();
$items->each->categories()->attach($request->categories);
public function store(ItemsValidatorRequest $request)
{
    // Here the $items_id will be a collection of ids not a single one
    $items_id = Item::select('items_id')->latest()->get();

    //Here the $item will be a collection of Item records
    //Since you are passing an array/collection of id to the find
    $item = Item::find($items_id);

    //This will error out as collection of Item records do not have categories relation/method on it
    $item->categories()->attach($request->categories);
}

所以试试这个

public function store(ItemsValidatorRequest $request)
{
    $items_id = Item::select('items_id')->latest()->first();
    $item = Item::findOrFail($items_id);
    $item->categories()->attach($request->categories);
}