Since one author can have many books, and one book can have many authors, such a connection is called βmany to manyβ and is organized through auxiliary table.
If you want to do everything as expected, you need to remove the authors_id field from the books table. Next, create a new book_author table with the book_id and author_id fields
Author models add a books method
class Author extends Model { //Π‘Π²ΡΠ·Ρ ΠΌΠ½ΠΎΠ³ΠΈΠ΅ ΠΊΠΎ ΠΌΠ½ΠΎΠ³ΠΈΠΌ public function books() { return $this->belongsToMany('App\Book', 'book_author'); //Π²ΡΠΎΡΠΎΠΉ Π°ΡΠ³ΡΠΌΠ΅Π½Ρ ΠΈΠΌΡ ΡΠ²ΡΠ·Π½ΠΎΠΉ ΡΠ°Π±Π»ΠΈΡΡ } }
Book models add the authors method
class Book extends Model { //Π‘Π²ΡΠ·Ρ ΠΌΠ½ΠΎΠ³ΠΈΠ΅ ΠΊΠΎ ΠΌΠ½ΠΎΠ³ΠΈΠΌ public function authors() { return $this->belongsToMany('App\Author', 'book_author'); //Π²ΡΠΎΡΠΎΠΉ Π°ΡΠ³ΡΠΌΠ΅Π½Ρ ΠΈΠΌΡ ΡΠ²ΡΠ·Π½ΠΎΠΉ ΡΠ°Π±Π»ΠΈΡΡ } }
Connection patterns are ready.
When adding a new book to the database:
$book = new Book(['title' => 'ΠΠ°Π·Π²Π°Π½ΠΈΠ΅ ΠΊΠ½ΠΈΠ³ΠΈ', 'publisher' => 'ΠΠΌΡ ΠΈΠ·Π΄Π°ΡΠ΅Π»Ρ']);
Add an arbitrary number of authors (id):
$book->authors()->attach(1, 2, 10, 40);
I also advise you to learn the methods of detach and sync.
Reading information from the database. We receive a collection of Book models, loading immediately connected Autor models.
$books = Book::with('autors')->get();
Next, referring to the autors property, each model can get a collection of models of authors of the book.
foreach $books as $book { foreach ($book->autors as $author) { dump($author); } }
You can do the reverse operation. Get the authors and download a coherent book model for each author.
$authors = Author::with('books')->get(); foreach $authors as $author { foreach ($author->books as $book) { dump($book); } }