SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

时间:2017-09-03 21:23:04

标签: php laravel

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

SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败(prj_testnote_tag,CONSTRAINT note_tag_note_id_foreign FOREIGN KEY({{ 1}})REFERENCES note_idtags))(SQL:插入idnote_tagnote_id)值(3,1))。< / p>

tag_id

NotesConroller

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');
    });

show.blade.php

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();
        }
    }

Tag.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>

我似乎无法找到我做错的事。显然外键有问题。

2 个答案:

答案 0 :(得分: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');
});

答案 1 :(得分:0)

确保您的模型中有tag_idnote_idfillable字段...