lundi 30 avril 2018

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 the method below the best way?

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire