user8075599
user8075599

Reputation:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

I have 2 tables (note_tag and tags). When I want to create a tag, I get the error message:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (prj_test.note_tag, CONSTRAINT note_tag_note_id_foreign FOREIGN KEY (note_id) REFERENCES tags (id)) (SQL: insert into note_tag (note_id, tag_id) values (3, 1)).

Table

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>

Tag.php

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

I can't seem to find what I'm doing wrong. Obviously there is something wrong with the foreign key.

Upvotes: 0

Views: 1231

Answers (2)

Leo
Leo

Reputation: 7420

make sure you have tag_id and note_id into fillable field in their models...

Upvotes: 0

fubar
fubar

Reputation: 17378

You have incorrectly defined your foreign keys. note_id references the tags table, and tag_id the notes table in your code.

It should instead be:

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

Upvotes: 1

Related Questions