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

Poo*_*aan 4 php laravel eloquent

我有一个模型叫做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');
    }
}
Run Code Online (Sandbox Code Playgroud)

这是Modell与 Model 的关系Brand

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

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

BadMethodCallException
Call to undefined method App\Models\BrandCodeModell::fromRawAttributes()
Run Code Online (Sandbox Code Playgroud)

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

    $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
        ]);
    });
Run Code Online (Sandbox Code Playgroud)

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

哪里有问题 ?

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

mik*_*n32 17

根据文档

自定义多对多枢轴模型应该扩展Illuminate\Database\Eloquent\Relations\Pivot该类

所以你的数据透视类应该是这样的:

<?php

namespace App\Models;

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

class BrandCodeModell extends Pivot
{
   //
}
Run Code Online (Sandbox Code Playgroud)

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