V
V
Velynder2019-02-16 23:42:29
ORM
Velynder, 2019-02-16 23:42:29

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

1 answer(s)
J
jazzus, 2019-02-17
@Velynder

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

Or all books with authors
$books=Book::with('authors')
                    ->withCount('authors')
                    ->get();

then you can
see that the authors and the number of authors have been added.
In template
@foreach ($books as $book)
          //количество авторов у книги
          {{$book->authors_count}}
          //имена авторов
          @foreach ($book->authors as $author)
            {{ $author->name }}
          @endforeach
      @endforeach

It's the same for authors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question