Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

annaoleksiuk's avatar

Getting many to many related data for an array of elements

Let's say I have two related tables, e.g. dogs and owners. If I had few owners which dogs names I'd like to get, how should I do it eloquently and dynamically?

0 likes
3 replies
gwp's avatar

Have you looked at the documentation? There are examples there.

http://laravel.com/docs/5.0/eloquent#relationships

More specifically:

http://laravel.com/docs/5.0/eloquent#many-to-many


You will need to define their relationships:

class Owners extends Model {

    public function dogs()
    {
        return $this->belongsToMany('App\Dogs');
    }

}


class Dogs extends Model {

    public function owners()
    {
        return $this->belongsToMany('App\Owners');
    }

}

You also need a dog_owner pivot table, with two columns:

  • dog_id
  • owner_id
1 like
annaoleksiuk's avatar

@gwp Yes, I have, and somehow I couldn't get an answer from there, therefore I look for some examples.

@mstnorris Thanks! Well, my intention was to narrow down the result to owners with a specific id, and I did as follows:

Owner::with('dogs')->whereNested( function($query) use ($ownerIdsArray)
{
    foreach($ownerIdsArray as $id)
    {
        $query->orWhere('id',$reg);
    }
})->get();

It works, but is it efficient?

1 like

Please or to participate in this conversation.