0

I'm trying to return all the attributes from my database that have a set foreign key (Attribute groups). I've set up all the relationships in my model but I'm unsure how to query these relationships using a collection or array.

AttributeGroup -

public function attribute()
{
    return $this->hasMany('App\Attribute', 'group_id');
}

Attribute -

public function attributeGroup()
{
    return $this->belongsTo('App\AttributeGroup');
}

My current query -

$page = Page::where('slug', $slug)->firstOrFail();

$groups = AttributeGroup::where('page_id', $page->id)->get()->toArray();

$atts = Attribute::where('group_id', $groups[0]['id'])->get();

This works because we have set the specific index of the array using $groups[0]

Is there a simple way I can pass an array through to the query using their relationships or is looping through the results and then passing my own array to the query the best approach?

$attributes = array();
foreach ($groups as $group){
   array_push($attributes, $group['id']);
}
$atts = Attribute::where('group_id', $attributes)->get();

1 Answer 1

3

$groups is a collection. Assume them as arrays on steroids. Therefore you can use the pluck() method to get those ids you need:

$page = Page::where('slug', $slug)->firstOrFail();
$groups = AttributeGroup::where('page_id', $page->id)->get();
$atts = Attribute::where('group_id', $groups->pluck('id'))->get();

Also if you've set your relationships correctly, you should be able to loop through $groups and access the attributes of those $groups. You can test it:

$groups = AttributeGroup::where('page_id', $page->id)->get();
dd($groups->first()->attributes);
Sign up to request clarification or add additional context in comments.

4 Comments

Ah that's brilliant I knew there would be a better approach thank you. If I used pluck and wanted to add something to that collection e.g the group_name would I need to go back to building up my own array? e.g using the query above the $groups collection has a group_name value inside, and I wanted to return and associate that with the $atts in the view
You can pass multiple columns to pluck() and then use map() to modify the collection as you need it to.
Ah so I'll be able to use map to add the $groups->name to each $atts result?
Every time you call ->get() you get a collection and all the methods are available to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.