Laravel 同步返回 SQLSTATE[42S22]

我正在尝试使用同步方法保存 2 个模型的 ID,但出现此错误:

消息:“SQLSTATE[42S22]:未找到列:1054 ‘字段列表’中的未知列‘cable_core_id’(SQL:插入closure_cores (cable_core_idcore_id)值(20、28))”

截屏

这是我发送到后端的数据

http://img1.mukewang.com/63aeb525000156d806870356.jpg

楷模

TitikClosur


class TitikClosur extends Model

{

    public function cores(){

        return $this->belongsToMany(CableCore::class, 'closure_cores', 'core_id');

    }

}

CableCore


class CableCore extends Model

{

    public function closures(){

        return $this->belongsToMany(TitikClosur::class, 'closure_cores', 'closure_id');

    }

}

控制器

public function store(Request $request)

{

  $titik = new TitikClosur;

  //...

  $titik->save();

  $titik->cores()->sync($request->cores, false);

  return....

}

图式

这就是我保存 ID 的表的样子


public function up()

    {

        Schema::create('closure_cores', function (Blueprint $table) {

            $table->id();

            $table->foreignId('core_id');

            $table->foreignId('closure_id');

            $table->timestamps();

        });

        Schema::table('closure_cores', function (Blueprint $table) {

            $table->foreign('core_id')->references('id')->on('cable_cores')->onUpdate('cascade')->onDelete('cascade');

            $table->foreign('closure_id')->references('id')->on('titik_closurs')->onUpdate('cascade')->onDelete('cascade');

        });

    }

任何的想法?


紫衣仙女
浏览 209回答 1
1回答

杨魅力

如果没有其他指示,laravel 期望数据透视表上的外键名称是表名的单数形式,并在末尾加上 _id。您在 belongsToMany 声明中犯了一个错误。您在两个语句中切换了键,cores() 返回的关系认为 core_id 指的是 TitikClosur 的 id,并假定 CableCore 模型必须具有键 cable_core_id,但在表中找不到它。此外,两个模型中的两个关系函数无法共享信息。所以你真的应该这样做:class TitikClosur extends Model{    public function cores(){        return $this->belongsToMany(CableCore::class, 'closure_cores', 'closure_id', 'core_id');    }}和class CableCore extends Model{    public function closures(){        return $this->belongsToMany(TitikClosur::class, 'closure_cores', 'core_id', 'closure_id');    }}回应您的更新:第二个错误通常意味着您的数据库中没有 ID 为 34 的 CableCore。
打开App,查看更多内容
随时随地看视频慕课网APP