【发布时间】: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');
}
}
这是Modell 与Brand 模型的关系:
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]);不起作用。
问题出在哪里?
如果您需要更多详细信息,请告诉我
【问题讨论】:
-
要使数据透视表工作,您必须在两个模型中定义为 belongsToMany 不属于。两个关系都应该有 belongsToMany 关系,如果它解决了你的问题,请尝试。
-
@AbdulRehman 我将其更改为: return $this->belongsToMany(Brand::class, 'brand_id', 'id');但我仍然有错误
-
当我清除 ->using(BrandCodeModell::class) 代码工作正常
-
为什么你必须为你使用数据透视表的关系指定哪个模型自动知道关系是否正确形成了数据透视表,如果它工作正常而不使用删除使用。