Including relationships | laravel-query-builder-go | Spatie       

 SPATIE  

laravel-query-builder-go
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-query-builder-go](https://spatie.be/docs/laravel-query-builder-go/v1)  Features  Including relationships

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-query-builder-go/v1) 

  Including relationships    
- [ Requirements ](https://spatie.be/docs/laravel-query-builder-go/v1/requirements)
- [ Introduction ](https://spatie.be/docs/laravel-query-builder-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/laravel-query-builder-go/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-query-builder-go/v1/questions-issues)
- [ Testing ](https://spatie.be/docs/laravel-query-builder-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-query-builder-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-query-builder-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-query-builder-go/v1/support-us)
- [ About us ](https://spatie.be/docs/laravel-query-builder-go/v1/about-us)

Features
--------

- [ Filtering ](https://spatie.be/docs/laravel-query-builder-go/v1/features/filtering)
- [ Sorting ](https://spatie.be/docs/laravel-query-builder-go/v1/features/sorting)
- [ Including relationships ](https://spatie.be/docs/laravel-query-builder-go/v1/features/including-relationships)
- [ Selecting fields ](https://spatie.be/docs/laravel-query-builder-go/v1/features/selecting-fields)

Advanced usage
--------------

- [ Extending query builder ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/extending-query-builder)
- [ Pagination ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/pagination)
- [ Multi value delimiter ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/multi-value-delimiter)
- [ Front-end implementation ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/front-end-implementation)
- [ Differences from PHP ](https://spatie.be/docs/laravel-query-builder-go/v1/advanced-usage/port-differences)

 Including relationships
=======================

###  On this page 

1. [ Basic usage ](#content-basic-usage)
2. [ Default includes ](#content-default-includes)
3. [ Disallowed includes ](#content-disallowed-includes)
4. [ Nested relationships ](#content-nested-relationships)
5. [ Including related model count ](#content-including-related-model-count)
6. [ Including related model exists ](#content-including-related-model-exists)
7. [ Including aggregate values (min, max, sum, avg) ](#content-including-aggregate-values-min-max-sum-avg)
8. [ Constraining aggregate includes ](#content-constraining-aggregate-includes)
9. [ Include aliases ](#content-include-aliases)
10. [ Custom includes ](#content-custom-includes)
11. [ Callback includes ](#content-callback-includes)
12. [ Selecting included fields ](#content-selecting-included-fields)
13. [ Include casing ](#content-include-casing)
14. [ Eloquent API resources ](#content-eloquent-api-resources)

Basic usage
-----------------------------------------------------------------------------------------

The `include` query parameter loads relationships with the resulting models. Relationships must be explicitly allowed.

```
// GET /users?include=posts,permissions
users, err := querybuilder.For(model.Query[User](), input).
    IncludeRelations("posts", "permissions").
    Get(r)
```

Define relationships using Laravel Go's model struct tags. `IncludeRelations` allows each given relationship, its parent paths, and the top-level `Count` and `Exists` convenience names. To expose only one exact name, use `AllowedIncludes(Relationship[User]("posts"))` instead.

Default includes
--------------------------------------------------------------------------------------------------------

Use `DefaultIncludes("posts")` after allowing the relationship, or start from a native subject with `.With("posts")`. Native subject loads always remain active. `DefaultIncludes` applies only when no nonempty include list is supplied.

Disallowed includes
-----------------------------------------------------------------------------------------------------------------

Unknown names return a `*QueryError` with `Kind == "includes"`. Setting `Config.IgnoreUnknownIncludes` ignores unknown names without invoking any callback for them. Application-owned defaults must also be allowlisted.

Nested relationships
--------------------------------------------------------------------------------------------------------------------

```
query := querybuilder.For(model.Query[User](), input).
    IncludeRelations("posts.comments")
```

This permits both `include=posts.comments` and `include=posts`. For polymorphic `morph_to` parents, register a `CustomInclude` using typed native `WithQuery` calls instead of a dotted path beyond the polymorphic segment.

Including related model count
-----------------------------------------------------------------------------------------------------------------------------------------------

`IncludeRelations("posts")` also permits `include=postsCount`. Your model needs a count field:

```
type User struct {
    ID int64 `json:"id"`
    Posts []Post `json:"posts,omitzero" model:"has_many"`
    PostsCount *int `json:"posts_count,omitzero" model:"count"`
}
```

Use `Count[User]("numberOfPosts", "posts")` for an explicit alias. Aggregate fields must exist on the model. Bad application declarations panic according to the native builder's contract, rather than waiting for a client to supply an arbitrary column name.

Including related model exists
--------------------------------------------------------------------------------------------------------------------------------------------------

`include=postsExists` loads a native existence aggregate. Declare a field such as `HasPosts *bool` tagged `model:"exists=posts"`. An explicit alias uses `Exists[User]("hasArticles", "posts")`.

Including aggregate values (min, max, sum, avg)
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

```
query := querybuilder.For(model.Query[User](), input).
    AllowedIncludes(querybuilder.Aggregate[User]("postsVotesSum", "sum", "posts", "votes"))
```

Use `"min"`, `"max"`, `"sum"` or `"avg"` as the function. Declare the matching model field, for example `PostsVotes *int` tagged `model:"sum=posts.votes"`. The JSON name belongs to your model's `json` tag. Request aliases do not dynamically add fields to Go structs.

Unlike count and exists convenience includes, aggregate column names are always explicit. Clients cannot choose the relationship, function or column. Pointer fields distinguish unloaded or absent values from loaded zero values.

Constraining aggregate includes
-----------------------------------------------------------------------------------------------------------------------------------------------------

Use `CustomInclude` and native `WithCountQuery` for constrained counts:

```
approved := querybuilder.CustomInclude("approvedPostsCount",
    func(q *model.Builder[User]) (*model.Builder[User], error) {
        return q.WithCountQuery("posts", func(posts *model.Builder[Post]) *model.Builder[Post] {
            return posts.Where("approved", "=", true)
        }), nil
    },
)
```

Laravel Go v0.1.0 does not expose constrained min, max, sum, avg or exists loaders. For these, use a custom query or response calculation in application code. Do not assume `WithCountQuery` changes the other aggregates.

Include aliases
-----------------------------------------------------------------------------------------------------

`Relationship[User]("articles", "posts")` allows `include=articles` while loading the native `posts` relationship. The returned JSON key remains the model's `json` tag. This alias does not automatically expose `articlesCount` or `articlesExists`. Register those explicitly when needed.

Custom includes
-----------------------------------------------------------------------------------------------------

Use a function or method value with `CustomInclude`. It can capture an application-owned profile and return a replacement native query. This is the extension point for custom eager-load behavior, not a second service registration.

Callback includes
-----------------------------------------------------------------------------------------------------------

```
recent := querybuilder.CustomInclude("recentPosts",
    func(q *model.Builder[User]) (*model.Builder[User], error) {
        return q.WithQuery("posts", func(posts *model.Builder[Post]) *model.Builder[Post] {
            return posts.Latest("id").Limit(3)
        }), nil
    },
)
```

Native limits apply per parent. Callback errors propagate unchanged.

Selecting included fields
-----------------------------------------------------------------------------------------------------------------------------------

Laravel Go v0.1.0 does not support sparse eager-loaded models. A related `fields[...]` request returns `ErrRelatedFields`. Use application response DTOs to control serialized attributes. See [selecting fields](selecting-fields).

Include casing
--------------------------------------------------------------------------------------------------

Include names match exactly. Choose your public spelling independently from the native relationship name using an alias. `IncludeRelations` uses the exact paths you provide. `CountSuffix` and `ExistsSuffix` control generated convenience names.

Eloquent API resources
--------------------------------------------------------------------------------------------------------------------------

Go does not use Eloquent API resource classes. Return your model or map it into an application-owned response DTO. Unloaded relationship fields can use `json:"posts,omitzero"`. Avoid returning sensitive columns merely because they were needed by a query.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
