I have the following working code that gives me a collection of a model type that each have any of the given relationship values (like a tag with id 1, 2 or 3):
<?php
public function getEntitiesWithRelationValues($entityType, $relations = []) {
$related = new EloquentCollection();
$locale = App::getLocale();
$entityType = new $entityType(); // bad?
// $entityType = new ReflectionClass($entityType); // not working
foreach ($relations as $relation => $modelKeys) {
if ($entityType->{$relation}()->exists()) {
$relatedClass = get_class($entityType->{$relation}()->getRelated());
$relationPrimaryKeyName = ($instance = new $relatedClass)->getQualifiedKeyName();
$relationEntities = $entityType::where('published->' . $locale, true)
->whereHas($relation, function (Builder $query) use($modelKeys, $relationPrimaryKeyName) {
$query->whereIn($relationPrimaryKeyName, $modelKeys);
})
->get()
->sortKeysDesc()
->take(10)
;
$related = $related->concat($relationEntities->except($related->modelKeys()));
}
}
return $related;
}
I feel $entityType = new $entityType();
is bad code because I dont want to create a new model. The reflection class throws the error "ReflectionClass undefined method {$relation}". How can I get the relationship data of a model type without actually loading/ instantiating a model?
A few weeks ago I asked something similar here but in that case I did have a model loaded.