【问题标题】:Call to undefined method App\Models\BrandCodeModell::fromRawAttributes() in Laravel在 Laravel 中调用未定义的方法 App\Models\BrandCodeModell::fromRawAttributes()
【发布时间】:2022-01-01 11:37:54
【问题描述】:

我有一个模型叫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-&gt;codeModell()-&gt;firstOrCreate会创建成功,但是这部分代码$brand-&gt;modells()-&gt;attach($mod-&gt;id, ['code_id' =&gt; $mod_code-&gt;id]);不起作用。

问题出在哪里?

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

【问题讨论】:

  • 要使数据透视表工作,您必须在两个模型中定义为 belongsToMany 不属于。两个关系都应该有 belongsToMany 关系,如果它解决了你的问题,请尝试。
  • @AbdulRehman 我将其更改为: return $this->belongsToMany(Brand::class, 'brand_id', 'id');但我仍然有错误
  • 当我清除 ->using(BrandCodeModell::class) 代码工作正常
  • 为什么你必须为你使用数据透视表的关系指定哪个模型自动知道关系是否正确形成了数据透视表,如果它工作正常而不使用删除使用。

标签: php laravel eloquent


【解决方案1】:

根据documentation

自定义多对多枢轴模型应扩展 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
{
   //
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2022-01-26
    • 2022-12-09
    • 2021-10-22
    • 2021-04-15
    • 2021-06-21
    • 1970-01-01
    • 2023-02-06
    相关资源
    最近更新 更多