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.
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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community