Answer the question
In order to leave comments, you need to log in
How to generate a request using Eloquent ORM?
Hello!
Help me understand Eloquent ORM in Laravel 5.7
There is a task to display a list of books from the database indicating the authors (there may be one or more).
I made 3 tables:
books [id, name]
authors [id, name]
author_book [author_id, book_id]
in both models I registered the relationship as belongsToMany
how to display a list of books or a list of authors, I know,
but how to display a list of books indicating their authors does not work.
And yet, I wanted to know what query to write to the database if a new book is entered. That the data was entered and in the crosstab?
Thank you everyone!
Answer the question
In order to leave comments, you need to log in
So, and look at the documentation?)) About belongstumeni
Recording in a pivot table using the attach () method
For example:
Requesting a specific book with authors
$book=Book::with('authors')
->withCount('authors')
->find($id);
$books=Book::with('authors')
->withCount('authors')
->get();
@foreach ($books as $book)
//количество авторов у книги
{{$book->authors_count}}
//имена авторов
@foreach ($book->authors as $author)
{{ $author->name }}
@endforeach
@endforeach
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question