2015-12-10 132 views
0

我有一個多對多的關係:Laravel多對多的關係:完整性約束違規

table 1 books 
table 2 authors 
table 3 books_authors 
     book_id, author_id 

問題是,當插入一個新的記錄,我得到這個錯誤:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'book_id' cannot be null (SQL: insert into books_authors_relationship (author_id , book_id , created_at , updated_at) values (3, , 2015-12-10 17:17:28, 2015-12-10 17:17:28))

作者模型

class Author extends Model 
{ 
    public function Book(){ 
     return $this->belongsToMany('App\Book','books_authors_relationship','book_id','author_id')->withTimestamps(); 
    } 
} 

噓K型

class Book extends Model 
    { 
    public function section(){ 
     return $this->belongsTo('App\Section','id'); 
    } 

     public function author(){ 
      return $this->belongsToMany('App\Author','books_authors_relationship','book_id','author_id')->withTimestamps(); 
     } 
    } 

書控制器

public function create($id) 
     { 
      $authors = Author::lists('first_name','id'); 
      $section_id = Section::find($id); 
      return view('books.create_book',compact('section_id','authors')); 

     } 
    public function store(storeBookRequest $request) 
     { 
      // dd($request->input('authors')); 
      $book_title = $request ->input('book_title'); 
      $book_edition = $request ->input('book_edition'); 
      $date_publication = $request ->input('date_publication'); 
      $book_isbn = $request ->input('book_isbn'); 
      $book_description = $request ->input('book_description'); 
      $file = $request ->file('image'); 
      $destinationPath = 'images'; 
      $filename = $file ->getClientOriginalName(); 
      $file ->move($destinationPath,$filename); 
      //join to author 
      $authorsIds = $request ->input('authors'); 


      $section_id = $request -> section_id; 


      $new_book = new Book; 
      $new_book ->book_title = $book_title; 
      $new_book ->book_edition = $book_edition; 
      $new_book ->date_publication = $date_publication; 
      $new_book ->book_isbn = $book_isbn; 
      $new_book ->book_description = $book_description; 
      $new_book ->image_name = $filename; 

      $new_book ->section_id = $section_id; 


      $new_book->author()->attach($authorsIds); 

      $new_book ->save(); 
      return redirect('admin_section'); 

     } 

回答

1

你必須保存$new_book之前,您可以附加作者。這是因爲新書沒有主鍵。主鍵在記錄實際存在於數據庫中時設置。

您的代碼:

$new_book ->section_id = $section_id; 

$new_book->author()->attach($authorsIds); 

$new_book->save(); 

應該是:

$new_book ->section_id = $section_id; 

if ($new_book->save()) { 
    $new_book->author()->attach($authorsIds); 
} 
+0

謝謝史蒂夫·鮑曼非常 – fido

+0

不是問題! :) –

相關問題