Error with "include alias" for a nested relationship
gelsner opened this issue · comments
Hi,
When defining "allowedIncludes" with an alias for a nested relationship the following error occurs:
Spatie\QueryBuilder\AllowedInclude::__construct(): Argument #1 ($name) must be of type string, null given, called in /var/www/vendor/spatie/laravel-query-builder/src/AllowedInclude.php on line 42
Example:
public function index() {
$projects = QueryBuilder::for(Project::class)
->allowedIncludes(
AllowedInclude::relationship(
'myAlias',
'foo.bar'
)
);
}
With a non-nested relationship it works completely fine, for example this works:
public function index() {
$projects = QueryBuilder::for(Project::class)
->allowedIncludes(
AllowedInclude::relationship(
'myAlias',
'foo'
)
);
}
The "allowedIncludes" with nested relationships WITHOUT an alias are also working fine, it's really just the combination that's failing.
Tested with version Query Builder 5.8.0 and Laravel 10.43.0
Hi @gelsner, we don't currently support defining an alias for the entire nested include. Instead the aliases are supposed to work for each individual section of the nested relationship. For example:
AllowedInclude::relationship('user.posts', 'authors.writtenPosts');
// user include is an alias for authors and users.posts is an alias for authors.wirttenPosts
I understand that this behavior might be confusing. If you're interested, I'm happy to merge a pull request to improve on this.