【问题标题】:Collection doesn't exist while trying to send data to two tables in Laravel 8尝试将数据发送到 Laravel 8 中的两个表时集合不存在
【发布时间】:2021-03-18 19:22:06
【问题描述】:

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

方法 Illuminate\Database\Eloquent\Collection:: 不存在

控制器

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');
}

【问题讨论】:

    标签: laravel laravel-8 laravel-collection


    【解决方案1】:

    $items_id 将是一个 id 数组,因此 Item::find($items_id) 将返回每个项目具有类别的项目的 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);
    

    【讨论】:

    • 嗨@Hafez Divandari。我有个问题。我把代码放进去,但现在我得到了同样的附加错误。有没有办法我也可以解决这个问题?
    • @Timmie282 您的代码中有错字,请将BelongsToMany 更改为belongsToMany
    • 已经这样做了,但没有修复错误。仍然得到错误 Method Illuminate\Database\Eloquent\Collection::attach does not exist.
    • @Timmie282 这不应该发生,你确定你使用的是带括号的each->categories()->attach 而不是each->categories->attach 吗?
    • 我目前有 $items->each->categories()->attach($request->categories)。所以我明白了,但我得到了错误
    【解决方案2】:
    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 2021-09-23
      • 2021-08-29
      • 1970-01-01
      • 2023-03-09
      • 2018-08-15
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多