archvist
archvist

Reputation: 722

Laravel relationship query where using array

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

Upvotes: 0

Views: 3377

Answers (1)

Ivanka Todorova
Ivanka Todorova

Reputation: 10229

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

Upvotes: 3

Related Questions