0

I have a multi-subdomain CRM. Each company gets their own subdomain.

There are companies and users. Addresses are a separate table and can be attached to either a user or a company by a pivot table.

This code returns all of the addresses in within the Subdomain::class model:

public function getAddresses() {
    return Address::wherehas('users', function($q) {
            $q->where('users.subdomain_id', $this->id);
        })->orWherehas('companies', function($q) {
            $q->where('companies.subdomain_id', $this->id);
        })->get();
}

I would like to convert this to a relation instead, something like:

public function addresses() {
    return $this->morphToMany(...);
}

Is morphToMany the correct method? How can I attach both companies and users tables to get all addresses that have a relation with the subdomain_id?

table schema:

addresses
- id
- address

address_pivot
- addressable_id
- addressable_type ('User' or 'Company')
- address_id

companies
- id
- company_name

users
- id
- name
iateadonut
  • 1,951
  • 21
  • 32
  • Can you also show us your addresses table schema / migration? I assume it's a polymorphic setup? – FatBoyXPC Aug 30 '19 at 05:07
  • `MorphToMany` would be fine, but I'm not sure you can use such a relation on the `Subdomain` model as it's not part of the `addressable_types`. What could work, but bear with me as I have never used this myself, is a `HasManyThrough` relationship on the `Subdomain` model with a `MorphToMany` relationship on the `User` and the `Company` models. Maybe have a look at [this question](https://stackoverflow.com/questions/43285779/laravel-polymorphic-relations-has-many-through) and its answers. – Namoshek Aug 30 '19 at 05:33

0 Answers0