Anyone?
Combining multiple hasManyThrough outputs
I have an application with multiple types of services which can be resold by a reseller to an end customer. For example I have the following models:
- DomainRegistration - domain registration services which can be resold to a customer by a reseller.
- WebhostingAccount - webhosting services which can be resold to a customer by a reseller.
- Reseller - the resellers.
- Customer - the end customer.
Both the DomainRegistration and WebhostingAccount models have the reseller relationship and a customer relationship:
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function reseller()
{
return $this->belongsTo('App\Reseller');
}
The Reseller model has it's reverse (hasMany) defined for both the DomainRegistration and WebhostingAccounts models.
Now I would like to add a function to the Reseller model to show all end customers the reseller has services for. So it should look for end customers with webhosting accounts and domain registrations, combined into one response without double customers.
It would in the ideal situation probably look something like this, but of course not with 2 return statements but one return statement returning the combined output:
public function customers()
{
return $this->hasManyThrough('App\Customer', 'App\DomainRegistration');
return $this->hasManyThrough('App\Customer', 'App\WebhostingAccount');
}
How can I do this?
I found a way to do this, however, I don't think this is the best way. I created the reseller->customers function using this custom attribute:
public function getCustomersAttribute()
{
return $this->domainRegistrations()->whereHas('customer')->with('customer')->get()->pluck('customer')
->union($this->webhostingAccounts()->whereHas('customer')->with('customer')->get()->pluck('customer'))->unique();
}
Please or to participate in this conversation.