laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Consistent with() and withCount() behaviour #2604

Closed PaolaRuby closed 3 years ago

PaolaRuby commented 3 years ago

Description:

Using "withCount()" with "as", i get the value, with an alias and using "with()" don't, example

$model::select()->withCount([
    'relation as relation_sum'=>function($q){ 
        $q->select('SUM(field)');
    }
])->get();

Using "with()" with "as", i get exception

$model::select()->with([
    'relation as relation_alias'=>function($q){ 

    }
])->get();

Alias a relationship without create a new "Relationships" function on model calling to the original

UPDATE: PR #31976 do the work and pass all test

    protected function eagerLoadRelation(array $models, $name, Closure $constraints)
    {
        // First we will determine if the name has been aliased using an "as" clause on the name
        // and if it has we will extract the actual relationship name and the desired name of
        // the resulting column. This allows multiple counts on the same relationship name.
        $segments = explode(' ', $name);

        unset($alias);

        if (count($segments) === 3 && Str::lower($segments[1]) === 'as') {
            [$name, $alias] = [$segments[0], $segments[2]];
        }

        // then we will "back up" the existing where conditions on the query so we can
        // add our eager constraints. Then we will merge the wheres that were on the
        // query back to it in order that any where conditions might be specified.
        $relation = $this->getRelation($name, $alias ?? null);

        $relation->addEagerConstraints($models);

        $constraints($relation);

        $relationshipName = $alias ?? $name;
        // Once we have the results, we just match those back up to their parent models
        // using the relationship instance. Then we just return the finished arrays
        // of models which have been eagerly hydrated and are readied for return.
        return $relation->match(
            $relation->initRelation($models, $relationshipName),
            $relation->getEager(), $relationshipName
        );
    }
themsaid commented 3 years ago

Hey,

I'm afraid we have no plans for this at the moment. Thanks for your contribution.