doushan5222 2019-01-03 05:02
浏览 126

Laravel无法添加或更新子行:外键约束失败

Before you start giving vote-down or mark as duplicated please read:

I have read Cannot add or update a child row a foreign key constraint fails and it is not my case,

  1. I have existing record
  2. my table supports cascade on delete.
  3. I also have my unsigned columns nullable

-- codes provided below

Issue

I am trying save related data in 3rd table named product_attributes with sync method, which gets product_id and attribute_id

Code

schema

public function up()
{
        Schema::create('product_attributes', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_id')->nullable()->unsigned();
            $table->integer('attribute_id')->nullable()->unsigned();
        });
        Schema::table('product_attributes', function (Blueprint $table) {
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
            $table->foreign('attribute_id')->references('id')->on('attributes')->onDelete('cascade');
        });
}

product model

public function attributes(){
        return $this->belongsToMany(Attribute::class, 'product_attributes', 'product_id', 'attribute_id');
}

attribute model

public function products(){
        return $this->belongsToMany(Product::class);
}

product controller

$product->save()
$product->attributes()->sync($request->attributes, false);

blade

<select class="form-control" name="attributes[]" id="attributes" multiple="multiple">
  @foreach($attributes as $attribute)
    <option value="{{ $attribute->id }}">{{ $attribute->title }}</option>
  @endforeach
</select>

Error

this is what I'm getting:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`shopping`.`product_attributes`, CONSTRAINT `product_attributes_attribute_id_foreign` FOREIGN KEY (`attribute_id`) REFERENCES `attributes` (`id`) ON DELETE CASCADE) (SQL: insert into `product_attributes` (`attribute_id`, `product_id`) values (*parameters, 3))

Anyone can help with that?

Update

Here is what I get when I send my data to controller

one

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 基于卷积神经网络的声纹识别
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
    • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
    • ¥15 CSAPPattacklab
    • ¥15 一直显示正在等待HID—ISP