在 Laravel 中调用未定义的方法 App\Models\BrandCodeModell::fromRawAttributes()

Call to undefined method App\Models\BrandCodeModell::fromRawAttributes() in Laravel

我有一个模型叫做 BrandCodeModell :

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BrandCodeModell extends Model
{
    use HasFactory;

    public function brand()
    {
        return $this->belongsTo(Brand::class, 'brand_id', 'id');
    }

    public function modell()
    {
        return $this->belongsTo(Modell::class, 'modell_id', 'id');
    }

    public function codeModell()
    {
        return $this->belongsTo(CodeModell::class, 'code_id', 'id');
    }
}

这是 ModellBrand 模型的关系:

public function modells()
{
   return $this->belongsToMany(Modell::class)->using(BrandCodeModell::class)
     ->withPivot('code_id');
}

当我尝试将新模型添加到数据库时,出现此错误:

BadMethodCallException
Call to undefined method App\Models\BrandCodeModell::fromRawAttributes()

这是我将模型保存到数据库的控制器:

    $brand = Brand::where('id', $id)->first();

    $brand->modells()->detach();

    $modells = collect($request['modells']);

    $modells->each(function ($item) use ($brand) {
        if (is_null($item['name'])) return;

        $mod = Modell::firstOrCreate([
            'name' => $item['name'],
            'sort' => $item['sort']
        ]);

        $mod_code = $mod->codeModell()->firstOrCreate([
            'name' => $item['code']
        ]);

        $brand->modells()->attach($mod->id, [
            'code_id' => $mod_code->id
        ]);
    });

在这段代码中,Modell::firstOrCreate$mod_code = $mod->codeModell()->firstOrCreate 将创建成功,但是这部分代码 $brand->modells()->attach($mod->id, ['code_id' => $mod_code->id]); 不起作用。

问题出在哪里?

如果您需要更多详细信息,请告诉我

根据 documentation:

Custom many-to-many pivot models should extend the Illuminate\Database\Eloquent\Relations\Pivot class

所以你的支点 class 应该是这样的:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\Pivot;

class BrandCodeModell extends Pivot
{
   //
}

但是,除非您在枢轴上添加其他方法 class,否则无需定义它; Laravel 将自动使用适当的枢轴 table。同样,它可能不需要导入 HasFactory 特征,因为条目将由相关模型创建自动创建。