TitasGailius / nova-search-relations

This package allow you to include relationship columns into Laravel Nova search query.
Other
352 stars 33 forks source link

Search for MorphTo relation #21

Closed ek0519 closed 4 years ago

ek0519 commented 4 years ago

Maybe can add morphTo relationship for search, thanks

giancanuz commented 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;
    }

}
TitasGailius commented 4 years ago

I won't add this feature unless Laravel starts supporting whereHas queries with morphTo relationships.

kamilkozak commented 4 years ago

I won't add this feature unless Laravel starts supporting whereHas queries with morphTo relationships.

What about whereHasMorph() ?

TitasGailius commented 4 years ago

Yes, I plan to re-visit this in the near future.