Krystian Polska
Krystian Polska

Reputation: 77

Laravel - how to list all keys on relation in collection?

I have something like:

$categories = Categories::with('sections')->get();

It gives me that collection:

img

As you can see on image I can access all "Y"'es by

dd($categories->pluck('id'));

Which gives me what I wanted, all ID's of items in this collection

enter image description here

But question is

How now get all ID's of "Y" ? which are attributes of relationship that belongs to each of these items

And I don't want to do that by foreaching. <---- I know how to do it that way.

But There must be better way, faster.

How to achieve it without needless foreaching this collection over and over :)?

Upvotes: 2

Views: 3574

Answers (2)

omitobi
omitobi

Reputation: 7334

You can simply retrieve all the ids in sections using dot notations using the example below:

You have:

$categories = Categories::with('sections')->get();

Getting the ids of all sections will be:

$sections = $categories->pluck('sections.*.id')->flatten()->values();

This will access the collections based on depth, sections-all-ids. and return a reindexed underlying array.

The same if you just need the sections, you can stop at sections.

PS: Just as @Jerodev mentioned, collections only wraps the php array in more useful ways, and the underlying pluck and many of these operations use loops.

Hope this is helpful

Upvotes: 5

Jerodev
Jerodev

Reputation: 33196

So, if I understand correctly you want all section ids for the categories in that collection?

You can use a second query for this using whereIn with the ids of these categories. Also, the with function is no longer needed.

$categories = Categories::get();
$sections = Section::whereIn('category_id', $categories->pluck('id'))->get();

Upvotes: 1

Related Questions