Laravel 多对多关系:违反完整性约束

fid*_*ido 1 mysql laravel

我有一个多对多的关系:

table 1 books  
table 2 authors  
table 3 books_authors  
        book_id, author_id
Run Code Online (Sandbox Code Playgroud)

问题是插入新记录时,出现此错误:

SQLSTATE [23000]:完整性约束违规:1048列'book_id'不能为空(SQL:INSERT INTO books_authors_relationshipauthor_idbook_idcreated_atupdated_at)的值(3,2015年12月10日17时17分二十八秒,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();
   }
}
Run Code Online (Sandbox Code Playgroud)

书型

   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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

图书控制器

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

        }
Run Code Online (Sandbox Code Playgroud)

Ste*_*man 5

您必须先保存 ,$new_book然后才能附加作者。这是因为新书没有主键。当记录实际存在于数据库中时设置主键。

您的代码:

$new_book ->section_id = $section_id;

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

$new_book->save();
Run Code Online (Sandbox Code Playgroud)

应该:

$new_book ->section_id = $section_id;

if ($new_book->save()) {
    $new_book->author()->attach($authorsIds);
}
Run Code Online (Sandbox Code Playgroud)