There are 2 tables: 1 is books 2 are authors. Books have a authors_id field which contains the id number of the author who wrote the book. I have a few questions. 1) How correctly in Laravel to bring to the books of the author who wrote the book ???? I brought the book but do not understand how to bring the author

namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Books; class BooksController extends Controller { public function index() { $booksList = Books::All(); return view('books')->with('booksList', $booksList); } } 

Question 2: How can I make it so that I can link several authors to one book (2 authors could write one book).

  • 1. Use the One-to-many relationship. 2. Use the Many-to-many relationship. - u_mulder
  • @u_mulder Method [belongsToMany] does not exist. - NONAME

1 answer 1

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