Support the ongoing development of Laravel.io →
Database Eloquent Queues

Hi all

I'm having some issues trying to set up a relationship for two Models. ExCompany and ExGroup. A company can belong to multiple groups so we have an intermediate table 'companies_groups' along with 'companies' and 'groups'.

These are existing tables from an old database so the naming conventions for Eloquent ORM aren't there. I would like to be able to select all companies belonging to a particular group id, but so far I'm not having much luck.

    // Below does not work. 
    $groups = ExGroup::find(76);
    $companies = $groups->companies()->where('active', 1)->limit(5)->get();

    // tables I have
    companies.id
    companies.active
    ...
    companies_groups.id
    companies_groups.company_id
    companies_groups.group_id
    ...
    groups.id
    groups.name
    ...

Can someone please tell me what kind of relationship I need to setup on both models.

Thank you.

Last updated 3 years ago.
0

You need the "belongsToMany" relationship.

public function companies() {
    return $this->belongsToMany('ExCompany', 'companies_groups', 'company_id', 'group_id');
}

I'm not sure from the top of my head if the order of the keys (company_id and group_id) is correct, maybe you will need to switch them.

0

HI ftiersch.

I had a problem with connecting to the wrong instance of a database so I was not getting the results I was expecting so the many to many set-up didn't appear to be working.

When I start by obtaining a single group first and then getting the companies, I end up with a unique set of companies. I have a problem when I try and select multiple groups first and then get the companies afterwards I end up with a collection of groups and doing groups->companies does not seem to work.

How can I obtain a unique set of companies in one collection by any number of groups they belong in?

Thanks

Edit : I found what i needed here.

http://stackoverflow.com/questions/18403135/eloquent-orm-eager-loading-distinct-records-in-many-to-many-relationship

Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

sonesay sonesay Joined 1 Dec 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.