2017-09-03 102 views
0

我有2個表(note_tag和tags)。當我想創建一個標籤,我得到錯誤信息:SQLSTATE [23000]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗

SQLSTATE [23000]:完整性約束違規:1452不能添加或更新子行,外鍵約束失敗(prj_testnote_tag,約束note_tag_note_id_foreign外鍵。 (note_id)參考文獻tagsid))(SQL:插入到note_tagnote_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> 

Tag.php

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

我似乎無法找到我做錯了什麼。顯然外鍵有問題。

回答

1

您錯誤地定義了您的外鍵。 note_id參考tags表和tag_idnotes表中的代碼。

應該改爲:

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

請確保您有tag_idnote_idfillable場在他們的模型...

相關問題