Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Selecting fields for included relations #959

Open
JaviLerma opened this issue Jul 19, 2024 · 2 comments
Open

Selecting fields for included relations #959

JaviLerma opened this issue Jul 19, 2024 · 2 comments

Comments

@JaviLerma
Copy link

Greetings from Argentina!
The Official docs says:

QueryBuilder::for(Post::class)  
    ->allowedFields('author.id', 'author.name')  
    ->allowedIncludes('author')  
    ->get();

GET /posts?include=author&fields[author]=id,name

Return all post but only id and name of the author, but it doesn't work. It fetches all the authors fields.

Relationships

User model:

public function posts(): HasMany
    {
        return $this->hasMany(Post::class, 'author_id');
    }}

Post model:

public function author(): BelongsTo
   {
       return $this->belongsTo(User::class, 'author_id');
   }

I am doing something wrong or its a bug?
Thanks

@luizmagao
Copy link

Estou passando pelo mesmo problema, não sei como resolver ainda.

@inmass
Copy link

inmass commented Sep 23, 2024

@JaviLerma @luizmagao
The current implementation doesn't work as expected due to several factors related to naming conventions and configuration:

  1. Relationship and Table Naming:
    By default, the query builder expects plural names for relations and table names. For example:

    • 'author' should be 'authors'
    • 'postComment' should be 'postComments'
  2. Using Singular Names:
    If you prefer to use singular naming for relationships, you need to publish the query-builder config file:
    php artisan vendor:publish --provider="Spatie\QueryBuilder\QueryBuilderServiceProvider" --tag="query-builder-config"
    Then, set convert_relation_names_to_snake_case_plural to false in the config file.

  3. Relation ID Fields:
    Ensure you add the relation id to the fields param

  4. Query Syntax:
    You can query related fields using either of these syntaxes:

  • Dot notation: fields=id,title,car_model_id,carModel.id,carModel.slug
  • Array notation: fields[carModel]=id,slug

These adjustments should resolve the issues with relationship querying and naming conventions in the current implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants