user3253002
user3253002

Reputation: 1671

retrieve items of a parent without nested loops

I want to have a collection with all books. Books belong to a bookstore and on the bookstore, there is a global scope.

When I do: bookstores = BookStore::all() and pass this to a view, I can do: pseudocode:

for each $bookstores as $bookstore
   for each $bookstore->books as $book
   end
end

How can I sort all my books by name for example (and not first by bookstore and then by book like in the example)

I can not use $books = Books::all(), because the scope is on Bookstore

Upvotes: 0

Views: 51

Answers (2)

Roj Vroemen
Roj Vroemen

Reputation: 1892

You can sort them while fetching:

BookStore::with(['books' => function($query) {
    $query->orderBy('name');
}])-get();

To answer your other question from the comment below about getting all the books. You'd run something like this:

$collection->pluck('books')->collapse()->sortBy('name')

pluck('books') basically grabs all the books from the bookStores. This will give something like this:

[[book-a, book-c], [book-b]]

collapse() will merge all nested arrays changing the result to:

[book-a, book-c, book-b]

As you can see the sorting is off again, to fix this sortBy('name') will be called resulting in the following:

[book-a, book-b, book-c]

As you can see this is 'quite' a task which you might not want to do in your view. The way I would do this would be to create a custom collection and add a method books() on there.

The method could look something like this:

public function books()
{
    return $this->pluck('books')->collapse()->sortBy('name');
}

Then you would have to make sure to overwrite the newCollection method in your Book model and return your custom collection. This would also end up in to the syntax you used in your example (in the comment below).

Upvotes: 2

Faisal
Faisal

Reputation: 162

Use Recursive function , you can get hierarchy with parent and child relation

Upvotes: 0

Related Questions