N
N
Nikolai Vasin2016-07-13 21:19:06
Laravel
Nikolai Vasin, 2016-07-13 21:19:06

Laravel. How to search in many to many relationship?

There is a list of books. Each book is associated with an author and a store. Each book can have multiple authors or stores, so many to many relationships are used here. There is a form with checkboxes: with authors, stores and books. When you click on these checkboxes, the corresponding books should be displayed. How to write a query so that a filter occurs simultaneously for both the author and the store. This can be done through whereHas, but how to do several whereHas at the same time and take into account that, for example, the author or store may not be selected.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WebDev, 2016-07-13
@talam0nal

$book = Book::select('id', 'name');
if ($author) {
  $book = $book->whereHas(...);
}

if ($shop) {
 $book = $book->whereHas(...);
}

$results = $book->get();

For example, yes. In whereHas, substitute the appropriate conditions for the selection.

E
Eugene, 2016-07-13
@Nc_Soft

Join

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question