I have the following relationships:
Usershave polymorphic many to many (morphedByMany) relationships withCustomers,Locations, andVendors.Customers,Locations, andVendorseach havehasManyorhasManyThroughrelationships withDatasets.
I'd like to get the Datasets that a given User has access to via its relationships. Also, some of the datasets through the different relationships might be the same, so I want a unique list.
I created the following method on my User model that works correctly (inspired by Laravel get a collection of relationship items):
public function accessibleDatasets()
{
$datasetsByCustomers = $this->customers()->with('datasets')->get()->pluck('datasets')->flatten();
$datasetsByLocations = $this->locations()->with('datasets')->get()->pluck('datasets')->flatten();
$datasetsByVendors = $this->vendors()->with('datasets')->get()->pluck('datasets')->flatten();
$datasets = $datasetsByCustomers;
$datasets = $datasets->merge($datasetsByLocations);
$datasets = $datasets->merge($datasetsByVendors);
return $datasets->unique();
}
Is there a "right way" or more efficient way to get this (besides using some sort of a reduce function for the merges)? Is loading the models, then flattening better? The associated values aren't going to change too often, so I can cache the results, but wanted to get some feedback.