Laravel有很多关系:完整性约束违规

时间:2015-12-10 17:23:35

标签: mysql laravel

我有很多关系:

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

问题是当插入新记录时,我收到此错误:

  

SQLSTATE [23000]:完整性约束违规:1048列' book_id'不能为空(SQL:插入books_authors_relationshipauthor_idbook_idcreated_atupdated_at)值(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();
   }
}

预订模型

   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 个答案:

答案 0 :(得分:3)

您必须先保存$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);
}