Closed ek0519 closed 4 years ago
This is how I solved. Hope author could be inspired and add official (better) support.
trait MySearchesRelations
{
use SearchesRelations;
public static function getCurrentSearchableRelationTraitMethod(Builder $query, string $relation) {
$model = $query->getModel();
return $model->{$relation}();
}
public static function getMorphCurrentEntityTypesTraitMethod(Builder $query, MorphTo $rel) {
$morphType = $rel->getMorphType();
$types = [];
foreach (DB::select("select distinct `".$rel->getMorphType()."` from `".$query->getQuery()->from."`") as $k => $v) {
$types[] = $v->{$morphType};
}
return $types;
}
/**
* Apply the relationship search query to the given query.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $search
* @return \Illuminate\Database\Eloquent\Builder
*/
protected static function applyRelationSearch(Builder $query, string $search): Builder
{
foreach (static::searchableRelations() as $relation => $columns) {
$rel = self::getCurrentSearchableRelationTraitMethod($query,$relation);
if ($rel instanceof MorphTo) {
$query->orWhereHasMorph($relation, self::getMorphCurrentEntityTypesTraitMethod($query,$rel), function ($query) use ($columns, $search) {
$query->where(static::searchQueryApplier($columns, $search));
});
}
else {
$query->orWhereHas($relation, function ($query) use ($columns, $search) {
$query->where(static::searchQueryApplier($columns, $search));
});
}
}
return $query;
}
}
I won't add this feature unless Laravel starts supporting whereHas
queries with morphTo
relationships.
I won't add this feature unless Laravel starts supporting
whereHas
queries withmorphTo
relationships.
What about whereHasMorph() ?
Yes, I plan to re-visit this in the near future.
Maybe can add morphTo relationship for search, thanks