【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint failsSQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败
【发布时间】:2018-02-12 03:42:07
【问题描述】:

我有 2 个表(note_tag 和 tags)。当我想创建标签时,我收到错误消息:

SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(prj_test.note_tag,CONSTRAINT note_tag_note_id_foreign FOREIGN KEY(note_id)参考tags (id)) (SQL: 插入note_tag (note_id, tag_id) 值 (3, 1))。

表格

Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('note_tag', function (Blueprint $table) {
        $table->integer('note_id')->unsigned()->index();
        $table->foreign('note_id')->references('id')->on('tags');
        $table->integer('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('notes');
    });

NotesConroller

class NotesController extends Controller

    {
        public function store(Request $request, Card $card){

            $this->validate($request, [
               'body' => 'required|unique:notes|min:2'
            ]);

            $note = new Note($request->all());
            $note->user_id = 1;
            $card->notes()->save($note);

            $note->tags()->attach($request->input("tags"));

            flash("Note is saved security.", "succes");
            return back();
        }

        public function edit(Note $note){
            return view('notes.edit', compact('note'));
        }

        public function update(Note $note, Request $request){
            $note->update($request->all());
            return back();
        }
    }

show.blade.php

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

标签.php

public function notes(){
    return $this->belongsToMany(Note::class);
}

我似乎找不到我做错了什么。显然外键有问题。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您错误地定义了外键。 note_id 在您的代码中引用 tags 表,tag_id notes 表。

    应该是:

    Schema::create('note_tag', function (Blueprint $table) {
        $table->integer('note_id')->unsigned()->index();
        $table->foreign('note_id')->references('id')->on('notes');
        $table->integer('tag_id')->unsigned()->index();
        $table->foreign('tag_id')->references('id')->on('tags');
    });
    

    【讨论】:

      【解决方案2】:

      确保在他们的模型中将tag_idnote_id 放入fillable 字段...

      【讨论】:

        猜你喜欢
        • 2021-09-29
        • 2014-01-09
        • 2017-04-13
        • 2017-11-23
        相关资源
        最近更新 更多