Tucker-Eric / EloquentFilter

An Eloquent Way To Filter Laravel Models And Their Relationships
http://tucker-eric.github.io/EloquentFilter
MIT License
1.72k stars 120 forks source link

Filtering relationships with dot notation #105

Closed williamjulianvicary closed 4 years ago

williamjulianvicary commented 5 years ago

I'm attempting to setup a relationship filter like this:

        return $this->related('user.location', 'name', 'LIKE', '%' . $name . '%');

However, it's pushing this back:

Call to undefined method App\Model\Project::user.location()

Which makes sense, before I go any further, I just wanted to check that this wasn't supported and I'm not missing something simple?

williamjulianvicary commented 5 years ago

I may still be missing something, but as far as I can tell this isn't yet supported.

I've extended the ModelFilter with this:

    /**
     * Get an empty instance of a related model.
     *
     * @param $relation
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function getRelatedModel($relation)
    {
        if (strpos($relation, '.') !== false) {
            return $this->getNestedRelatedModel($relation, $this->query->getModel());
        }

        return $this->query->getModel()->{$relation}()->getRelated();
    }

    /**
     * Get a nested model.
     *
     * @param $relation
     * @param Model $model
     */
    public function getNestedRelatedModel($relation, $model)
    {
        if (strpos($relation, '.') !== false) {
            $pos = strpos($relation, '.');
            $model = $model->{substr($relation, 0, $pos)}()->getRelated();
            return $this->getNestedRelatedModel(substr($relation, $pos+1, strlen($relation)), $model);
        }

        return $model->{$relation}()->getRelated();
    }

Essentially walking through the related models to discover the model in question. I'm not convinced this won't have side effects elsewhere, as I see there is something going on with $this->_joinedTables which may run into a block (as the table is technically joined, but it's deep, so if a different relation was attempted to be used that used the same underlying table, there may be a conflict, I THINK).

Hopefully this helps!

Tucker-Eric commented 4 years ago

Ahhh, ya you are absolutely correct. Will have a patch coming shortly for this.