为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 同步返回 SQLSTATE[42S22]

Laravel 同步返回 SQLSTATE[42S22]

PHP
紫衣仙女 2022-12-30 17:53:25
我正在尝试使用同步方法保存 2 个模型的 ID,但出现此错误:消息:“SQLSTATE[42S22]:未找到列:1054 ‘字段列表’中的未知列‘cable_core_id’(SQL:插入closure_cores (cable_core_id,core_id)值(20、28))”截屏这是我发送到后端的数据楷模TitikClosurclass TitikClosur extends Model{    public function cores(){        return $this->belongsToMany(CableCore::class, 'closure_cores', 'core_id');    }}CableCoreclass 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');        });    }任何的想法?
查看完整描述

1 回答

?
杨魅力

TA贡献1811条经验 获得超5个赞

如果没有其他指示,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。


查看完整回答
反对 回复 2022-12-30
  • 1 回答
  • 0 关注
  • 84 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信