跳至正文

Database: Model Relationships ​

Introduction ​

Database tables are often related to one another. For example, a blog post belongs to the user who wrote it, and it may have many comments. Relationships let you declare these connections on your models once. You may then load the related models, filter by them, and create them without writing the join queries yourself.

A relationship is a field of a model with a model tag that names the kind of relationship. For example, this Post belongs to a user and has many comments:

go
// models/post.go
package models

import "time"

type Post struct {
	ID          int64      `json:"id"`
	UserID      int64      `json:"user_id"`
	Title       string     `json:"title"`
	Votes       int64      `json:"votes" db:",default"`
	PublishedAt *time.Time `json:"published_at"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`

	User     *User     `json:"user,omitzero" model:"belongs_to"`
	Comments []Comment `json:"comments,omitzero" model:"has_many"`
}
go
// models/comment.go
package models

type Comment struct {
	ID       int64  `json:"id"`
	PostID   int64  `json:"post_id"`
	UserID   int64  `json:"user_id"`
	Body     string `json:"body"`
	Approved bool   `json:"approved" db:",default"`

	User *User `json:"user,omitzero" model:"belongs_to"`
}

Once a relationship is declared, you can eager-load it when you query the model. This handler loads a post with its author and its comments, then reads the author and the comments as the post's own fields:

go
package posts

import (
	"go.laravel.com/model"
	"go.laravel.com/web"

	"app/models"
)

func Show(r *web.Request) *web.Response {
	post, err := model.Query[models.Post]().
		With("user", "comments").
		FromRoute(r, "post")
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(map[string]any{
		"title":    post.Title,
		"author":   post.User.Name,
		"comments": len(post.Comments),
	})
}

Reading a relationship field never runs a query behind the scenes. You load the relationships you need up front with With, or query them directly with model.Related, and every query takes a context such as r. So you can always see where your code talks to the database, and a loop over posts can't quietly run a query for each post.

Declaring relationships ​

Each kind of relationship holds either one related model or many of them. For example, a post has one author but many comments, so its User field is a pointer and its Comments field is a slice. To declare a relationship, tag a field with the kind of relationship and give the field the type that this table lists:

TagField typeHolds
model:"has_one"*ProfileThe model whose foreign key refers to this one
model:"has_many"[]CommentThe models whose foreign keys refer to this one
model:"belongs_to"*UserThe model this one's foreign key refers to
model:"belongs_to_many"[]TagThe models a join table links to this one
model:"has_one_through,through=car.owner"*OwnerThe model reached through another relationship, such as the owner of a mechanic's car
model:"has_many_through,through=environments.deployments"[]DeploymentThe models reached through another relationship, such as the deployments of a project's environments
model:"morph_to"Commentable, an interfaceThe model that this one's type and key columns refer to, which may be one of several types
model:"morph_one,name=imageable"*ImageThe model whose type and key columns refer to this one
model:"morph_many,name=commentable"[]CommentThe models whose type and key columns refer to this one
model:"morph_to_many,name=taggable"[]TagThe models a polymorphic join table links to this one
model:"morphed_by_many,name=taggable"[]PostThe models of one type that a polymorphic join table links to this one

The morph kinds are polymorphic relationships, which refer to more than one kind of model, such as a comment on either a post or a video.

A relationship field isn't a database column, so a query leaves the field empty until you ask for the relationship with eager loading. A relationship's name is its field's name in snake case, as a column's name is, so Comments is comments and BlogPosts is blog_posts. You pass that name to With, Has, and the other methods on this page. If you misspell a relationship's name, Laravel panics and lists the relationships the model does have:

text
model: Post has no relationship "coments": its relationships are user, comments

Relationships follow Laravel's naming conventions for keys and tables. If your columns have other names, you may name them in the tag after the kind and a comma, as in model:"belongs_to,foreign_key=author_id".

Has one and has many ​

A has_many relationship connects a model to any number of related rows. For example, a user has many posts, and each post's user_id column holds the user's ID. By default, Laravel expects the foreign key on the related table to be this model's type name in snake case followed by _id, such as user_id for User and blog_post_id for BlogPost. To give the User model in your application its posts, add a field:

go
// models/user.go
type User struct {
	ID    int64  `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
	// Other fields...

	Posts []Post `json:"posts,omitzero" model:"has_many"`
}

A has_one relationship follows the same convention when each user has at most one related row, such as a Profile with a user_id column. Its field is a pointer, which stays nil when the user has no profile:

go
Profile *Profile `json:"profile,omitzero" model:"has_one"`

If the related model's column has another name, or holds something other than this model's ID, name the columns with foreign_key and local_key. For example, this relationship holds the posts whose author_email column matches the user's email:

go
AuthoredPosts []Post `json:"authored_posts,omitzero" model:"has_many,foreign_key=author_email,local_key=email"`

Belongs to ​

A belongs_to relationship is the other side of a has_one or has_many relationship. It reads a foreign key column on this model that holds the related model's ID. By default, the foreign key is the relationship's name followed by _id, so User reads user_id. If the column is nullable, such as a post's editor_id, make the key field a pointer. A post without an editor then loads a nil Editor:

go
// models/post.go
type Post struct {
	ID       int64  `json:"id"`
	UserID   int64  `json:"user_id"`
	EditorID *int64 `json:"editor_id"`

	User   *User `json:"user,omitzero" model:"belongs_to"`
	Editor *User `json:"editor,omitzero" model:"belongs_to"`
}

If your columns don't follow the convention, name them in the tag. foreign_key is this model's column, and owner_key is the related model's column that it matches. For example, this Author relationship reads the post's author_email column, which holds a user's email instead of their ID:

go
Author *User `json:"author,omitzero" model:"belongs_to,foreign_key=author_email,owner_key=email"`

Belongs to many ​

Some relationships go both ways. For example, a post may have many tags, and each tag may be on many posts. A belongs_to_many relationship links two models like these through a join table, where each row holds the key of one post and the key of one tag. Declare the relationship on both models:

go
// models/post.go
type Post struct {
	ID int64 `json:"id"`
	// ...

	Tags []Tag `json:"tags,omitzero" model:"belongs_to_many"`
}
go
// models/tag.go
type Tag struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`

	Posts []Post `json:"posts,omitzero" model:"belongs_to_many"`
}

By default, Laravel expects these names for the join table and its columns:

OptionDefaultFor Post and Tag
tableBoth models' type names in snake case, in alphabetical order, joined by _post_tag
parent_columnThis model's type name in snake case, followed by _idpost_id
related_columnThe related model's type name in snake case, followed by _idtag_id

Create the join table in a migration. Give its two key columns a unique index so that a post can't get the same tag twice:

go
// database/migrations/2026_11_10_130000_create_post_tag_table.go
package migrations

import (
	"context"

	"go.laravel.com/schema"
)

func createPostTagTable(ctx context.Context) error {
	return schema.Create(ctx, "post_tag", func(table *schema.Blueprint) {
		table.ForeignID("post_id").Constrained().CascadeOnDelete()
		table.ForeignID("tag_id").Constrained().CascadeOnDelete()

		table.Unique("post_id", "tag_id")
	})
}

If your join table or its columns have other names, pass the options in the tag. For example, this relationship reads a user's roles from a role_user table whose user column is member_id:

go
Roles []Role `json:"roles,omitzero" model:"belongs_to_many,table=role_user,parent_column=member_id,related_column=role_id"`

Has one of many ​

Sometimes a model has many related models, but you often need only one of them. For example, a user may have placed many orders, while their account page shows only the latest one. Declare a has_one field with the of_many option next to the has_many field:

go
// models/user.go
type User struct {
	ID int64 `json:"id"`
	// ...

	Orders      []Order `json:"orders,omitzero" model:"has_many"`
	LatestOrder *Order  `json:"latest_order,omitzero" model:"has_one,of_many=latest"`
}

LatestOrder holds the order with the largest ID, and of_many=oldest would pick the order with the smallest ID. The field stays nil for a user who hasn't placed an order.

To pick by another column, such as when the order was placed or how much it cost, name the column after max: or min:. These relationships pick the most recently placed order and the most expensive order:

go
LatestOrder  *Order `json:"latest_order,omitzero" model:"has_one,of_many=max:placed_at"`
LargestOrder *Order `json:"largest_order,omitzero" model:"has_one,of_many=max:price"`

If two orders share the largest price, Laravel picks the order with the larger ID, and min: picks the order with the smaller ID. An order whose column is NULL is never picked. morph_one and has_one_through relationships accept of_many too.

A has_one relationship with of_many works like any other has_one relationship with With, WithCount, and WhereHas. A condition applies to the order that the relationship picked. For example, this query finds the users whose latest order is still pending, not the users who have any pending order:

go
waiting, err := model.Query[models.User]().
	WhereHas("latest_order", func(q *model.Builder[models.Order]) *model.Builder[models.Order] {
		return q.WhereEq("status", "pending")
	}).
	With("latest_order").
	Get(r)

Constrained eager loads also apply after Laravel picks the order, so WithQuery("latest_order", ...) loads each user's latest order only when that order meets the clauses. If you want the latest order among the orders that meet a condition, such as the latest paid order, give the relationship a scope. Laravel applies the scope before it picks the order.

Has one through and has many through ​

A through relationship reaches distant rows through an intermediate model. For example, a project may have many environments, and each environment may have many deployments. The deployments table has no column that refers to a project, but a project's deployments are the deployments of its environments. Declare a has_many_through relationship that goes through the project's environments:

go
// models/project.go
type Project struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`

	Environments []Environment `json:"environments,omitzero" model:"has_many"`
	Deployments  []Deployment  `json:"deployments,omitzero" model:"has_many_through,through=environments.deployments"`
}
go
// models/environment.go
type Environment struct {
	ID        int64  `json:"id"`
	ProjectID int64  `json:"project_id"`
	Name      string `json:"name"`

	Deployments []Deployment `json:"deployments,omitzero" model:"has_many"`
}

The through option names two relationships joined by a dot. The first is this model's relationship to the intermediate model, and the second is the intermediate model's relationship to the related model. Each may be a has_one, has_many, morph_one, or morph_many relationship without of_many. Laravel takes the keys and columns from those two relationships, so a through relationship has no key or column options.

A has_one_through relationship follows the same pattern when there's at most one related row. For example, a mechanic has one car and a car has one owner, so a mechanic's CarOwner goes through the mechanic's car relationship:

go
// models/mechanic.go
Car      *Car   `json:"car,omitzero" model:"has_one"`
CarOwner *Owner `json:"car_owner,omitzero" model:"has_one_through,through=car.owner"`

To pick one of many rows through the intermediate model, such as a project's latest deployment in any environment, put of_many on the through relationship itself rather than on the intermediate model's relationship:

go
LatestDeployment *Deployment `json:"latest_deployment,omitzero" model:"has_one_through,through=environments.deployments,of_many=latest"`

You may use a through relationship with With, WithCount, Has, WhereHas, and model.Related, as you would a has_many or has_one relationship. Its query joins the intermediate table, so you may also filter by that table's columns. For example, this query reads only the project's production deployments:

go
deployments, err := model.Related[models.Deployment](&project, "deployments").
	WhereEq("environments.name", "production").
	Get(r)

A through relationship is read-only, because Laravel can't tell which environment a new deployment should belong to. Create the deployment through its environment instead, as in model.CreateRelated(r, &environment, "deployments", &deployment). If you call model.CreateRelated through the project's deployments relationship, Laravel panics and points you to Environment's deployments relationship.

Filtered relationships ​

Sometimes you want a relationship that holds only some of the related rows. For example, a user's profile page may list only their published posts, and the admin page may need only the roles a user administers. Write a method on the related model that adds the conditions, shaped like a scope, and name the method in the relationship's scope option next to the unfiltered relationship:

go
// models/post.go
func (Post) Published(q *model.Builder[Post]) *model.Builder[Post] {
	return q.WhereNotNull("published_at")
}
go
// models/user.go
type User struct {
	ID int64 `json:"id"`
	// ...

	Posts          []Post `json:"posts,omitzero" model:"has_many"`
	PublishedPosts []Post `json:"published_posts,omitzero" model:"has_many,scope=Published"`
}

PublishedPosts works like any other has_many relationship, but it reads only published posts. The same goes for model.Related, With, WithCount, Has, WhereHas, DoesntHave, and the aggregates. For example, this query retrieves every user who has published a post, along with those published posts:

go
authors, err := model.Query[models.User]().Has("published_posts").With("published_posts").Get(r)

Every kind of relationship except morph_to accepts scope. If the tag names a method that doesn't exist, or a method that doesn't take and return the related model's builder, Laravel panics the first time you use the relationship and names the method it expects.

Filtering join-row columns ​

A belongs_to_many scope may also filter by the columns of the join table. For example, this scope keeps the roles whose role_user row holds the level admin:

go
// models/role.go
func (Role) Administered(q *model.Builder[Role]) *model.Builder[Role] {
	return q.WhereEq("role_user.level", "admin")
}
go
// models/user.go
AdminRoles []Role `json:"admin_roles,omitzero" model:"belongs_to_many,table=role_user,scope=Administered"`

Creating and updating through filtered relationships ​

A write through a filtered relationship doesn't set the columns that its scope checks, so you need to set those columns yourself. For example, model.CreateRelated(r, &user, "published_posts", &post) creates a draft unless you set the post's PublishedAt. Likewise, model.Attach(r, &user, "admin_roles", role.ID) inserts a join row whose level is the column's default. To grant the role as an admin, pass the level with model.AttachWith:

go
err := model.AttachWith(r, &user, "admin_roles", map[int64]db.Values{
	role.ID: {"level": "admin"},
})

When you sync join rows through a filtered belongs_to_many relationship, model.Detach, Sync, Toggle, and UpdateJoinRow change only the join rows of the roles that the scope keeps. So this call replaces the user's admin roles and leaves their other roles alone:

go
_, err := model.Sync(r, &user, "admin_roles", form.RoleIDs)

Because a user has only one role_user row for each role, attaching a role that the user already holds at another level fails on the join table's unique index. To promote an existing membership instead, update its join row through the unfiltered relationship:

go
err := model.UpdateJoinRow(r, &user, "roles", role.ID, db.Values{"level": "admin"})

Combining filters with other relationships ​

The scope applies wherever you use the relationship, so you may combine it with of_many and with through relationships:

go
// Picks the latest published post...
LatestPublishedPost *Post `json:"latest_published_post,omitzero" model:"has_one,of_many=latest,scope=Published"`

// Reads only the comments on the user's published posts...
PublishedComments []Comment `json:"published_comments,omitzero" model:"has_many_through,through=published_posts.comments"`

A nested route that finds a model through a filtered relationship, as in model.Related[models.Post](&user, "published_posts").FromRoute(r, "post"), also finds only the rows the scope keeps.

Sometimes you want one model's related models with clauses of their own. model.Related starts a query of one model's related models. Its type argument is the related model, and it takes a pointer to the model and the relationship's name. For example, model.Related[models.Post](user, "posts") returns a model query that already keeps only that user's posts, so you may use every clause and read method on it. This handler returns the signed-in user's drafts, newest first:

go
func Drafts(r *web.Request) *web.Response {
	user := r.User[models.User]()

	drafts, err := model.Related[models.Post](user, "posts").
		WhereNull("published_at").
		Latest("created_at").
		Get(r)
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(drafts)
}

Counting and deleting related rows follow the same pattern:

go
count, err := model.Related[models.Post](user, "posts").Count(r)

deleted, err := model.Related[models.Post](user, "posts").WhereLt("votes", -10).Delete(r)

Laravel joins your conditions to the condition that keeps this user's posts with and. A condition that you add with OrWhere would be joined with or instead, and would match other users' posts too. To combine conditions with or, put them in a WhereGroup. For example, this query reads the user's popular posts and their posts titled "Hello", and never another user's post:

go
posts, err := model.Related[models.Post](user, "posts").
	WhereGroup(func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereGt("votes", 100).OrWhereEq("title", "Hello")
	}).
	Get(r)

model.Related works with every kind of relationship except morph_to. Through a belongs_to_many relationship, the query reads the related models through the join table. For example, this query reads a post's tags in alphabetical order:

go
tags, err := model.Related[models.Tag](&post, "tags").OrderBy("name").Get(r)

Sometimes you want only the models that have related models. For example, an authors page might list only the users who have written a post. Pass the relationship to Has. To find the users who haven't written a post, use DoesntHave:

go
authors, err := model.Query[models.User]().Has("posts").Get(r)

lurkers, err := model.Query[models.User]().DoesntHave("posts").Get(r)

To keep the models whose related models match a single condition without writing a callback, use WhereRelation or WhereRelationEq. These queries find users who have written a post with more than 10 votes or a published post:

go
popular, err := model.Query[models.User]().
	WhereRelation("posts", "votes", ">", 10).
	Get(r)

publishers, err := model.Query[models.User]().
	WhereRelationEq("posts", "published", true).
	Get(r)

When a filter needs more than one condition, a scope, or a morph_to relationship, use WhereHas. It takes a function that receives a builder for the related model and adds clauses to its query:

go
popular, err := model.Query[models.User]().
	WhereHas("posts", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereGt("votes", 10).WhereNotNull("published_at")
	}).
	Get(r)

WhereDoesntHave and WhereDoesntHaveRelation (along with WhereDoesntHaveRelationEq) are the opposites. This table lists what each method keeps when you filter users by their posts:

MethodKeeps the models that have
Has("posts")At least one post
WhereRelation("posts", "votes", ">", 10)At least one post matching the condition
WhereHas("posts", query)At least one post that query matches
DoesntHave("posts")No posts
WhereDoesntHaveRelation("posts", "status", "=", "flagged")No post matching the condition, which includes having no posts
WhereDoesntHave("posts", query)No post that query matches, which includes having no posts

A dotted name looks through each relationship in turn. For example, Has("posts.comments") keeps the users who have a post with at least one comment, and WhereRelationEq("posts.tags", "name", "go") keeps the users who have a post tagged go.

Each of these methods joins its condition to the ones before it with and. To join it with or instead, use OrHas, OrDoesntHave, OrWhereRelation, OrWhereRelationEq, OrWhereDoesntHaveRelation, OrWhereDoesntHaveRelationEq, OrWhereHas, or OrWhereDoesntHave. For example, this query finds the users who have either written a post with more than 10 votes or have a laravel.com address:

go
users, err := model.Query[models.User]().
	WhereLike("email", "%@laravel.com", false).
	OrWhereRelation("posts", "votes", ">", 10).
	Get(r)

When checking for one related model isn't enough, such as for a leaderboard that lists only the users who have written three posts or more, pass HasCount the relationship, an operator, and a count. Laravel compares each user's number of posts with the count:

go
prolific, err := model.Query[models.User]().HasCount("posts", ">=", 3).Get(r)

To count only some of the related models, use WhereHasCount, which also takes a function that adds clauses to the related model's query. This query finds the users who have at least three posts with more than 10 votes each:

go
popular, err := model.Query[models.User]().
	WhereHasCount("posts", ">=", 3, func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereGt("votes", 10)
	}).
	Get(r)

The function you pass to WhereHas may count too. For example, this query finds the users who have a post with at least five comments:

go
discussed, err := model.Query[models.User]().
	WhereHas("posts", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.HasCount("comments", ">=", 5)
	}).
	Get(r)

The operator may be =, <>, <, <=, >, or >=. If zero meets the comparison, as in HasCount("posts", "<", 3), the query also keeps the users who have no posts at all.

A leaderboard also lists its most prolific authors first. OrderByCountDesc sorts the models by how many related models each one has, and OrderByCount sorts fewest first. A user without posts counts as zero. This query retrieves the ten users with the most posts, and sorts users with the same count by name:

go
busiest, err := model.Query[models.User]().
	OrderByCountDesc("posts").
	OrderBy("name").
	Limit(10).
	Get(r)

A filtered relationship counts only the rows its scope keeps, so OrderByCountDesc("published_posts") ranks users by their published posts.

Eager loading ​

Suppose a page lists 25 posts with each author's name. If you found each post's author in a loop, you'd run 26 queries: one for the posts and one for each author. Eager loading needs only two queries. Pass the relationship's name to With, and Laravel loads the relationship into every model the query returns:

go
posts, err := model.Query[models.Post]().With("user").Latest("created_at").Get(r)
if err != nil {
	return web.Fail(err)
}

for _, post := range posts {
	fmt.Println(post.Title, "by", post.User.Name)
}

The query for the posts runs first. Then one more query loads the authors of all those posts, and Laravel puts each author in its post's User field. To load several relationships, name each one, as in With("user", "comments"). Each relationship runs one query, however many posts there are.

With works with every method that reads models, including Get, First, Find, Sole, ChunkByID, LazyByID, and the paginators.

Nested eager loading ​

Sometimes you need the relationships of the related models too, such as the author of each comment on a post. To load them, join the relationship names with a dot. This query loads each post's author, each post's comments, and each comment's author:

go
posts, err := model.Query[models.Post]().With("user", "comments.user").Get(r)

Each level runs one query, so this example runs four queries: the posts, their authors, their comments, and the comments' authors.

Constraining eager loads ​

Sometimes you don't need every related model. For example, a list of authors might show only each author's three most recent published posts. To filter, sort, or limit the related models that eager loading fetches, use WithQuery. It takes the relationship's name and a function that receives a builder for the related model and adds clauses to the query that loads them:

go
users, err := model.Query[models.User]().
	WithQuery("posts", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereNotNull("published_at").Latest("published_at").Limit(3)
	}).
	Get(r)

A Limit or Offset applies to each user's posts, not to all the posts together, so every user gets up to three posts of their own. When you limit a load, also give it an order so that you choose which posts each user gets.

The builder in the function is a model query of its own, so you may call With on it to load the related models' relationships. For example, this query loads each user's three most recent published posts, along with only the approved comments on those posts:

go
users, err := model.Query[models.User]().
	WithQuery("posts", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.
			WhereNotNull("published_at").
			Latest("published_at").
			Limit(3).
			WithQuery("comments", func(q *model.Builder[models.Comment]) *model.Builder[models.Comment] {
				return q.WhereEq("approved", true)
			})
	}).
	Get(r)

If you pass a dotted name to WithQuery, the clauses apply only to the last relationship, and Laravel loads the relationships before it in full. For example, WithQuery("posts.comments", ...) loads every post of each user, but only the comments that match the clauses.

Sometimes you need to know how many related models there are without loading them. For example, a list of posts might show how many comments each post has. Give the model a pointer field named for the relationship followed by Count, and tag the field model:"count":

go
// models/post.go
type Post struct {
	// ...

	Comments      []Comment `json:"comments,omitzero" model:"has_many"`
	CommentsCount *int      `json:"comments_count,omitzero" model:"count"`
}

Using *int with omitzero leaves comments_count out of JSON responses when a query doesn't count comments, while a loaded count of zero still encodes as "comments_count": 0. You may use a plain int instead if you don't serialize the model or don't need to distinguish an unloaded count from zero.

Then pass the relationship to WithCount, and Laravel sets each post's CommentsCount field:

go
posts, err := model.Query[models.Post]().WithCount("comments").Get(r)
if err != nil {
	return web.Fail(err)
}

for _, post := range posts {
	fmt.Println(post.Title, "has", *post.CommentsCount, "comments")
}

To count only some of the related models, use WithCountQuery. Like WithQuery, it takes a function that adds clauses to the related model's query. For example, this query counts each post's approved comments:

go
posts, err := model.Query[models.Post]().
	WithCountQuery("comments", func(q *model.Builder[models.Comment]) *model.Builder[models.Comment] {
		return q.WhereEq("approved", true)
	}).
	Get(r)

Sums, extremes, averages, and existence ​

Besides counting related models, Laravel can add up, average, or pick the largest or smallest value of a related model's column without loading the related models. For example, an author directory might show each author's total votes across their posts and when they last published. Give the model a field for each value, and tag the field with the function, the relationship, and the related model's column:

go
// models/user.go
type User struct {
	ID int64 `json:"id"`
	// ...

	Posts         []Post     `json:"posts,omitzero" model:"has_many"`
	PostsVotes    *int64     `json:"posts_votes,omitzero" model:"sum=posts.votes"`
	LastPublished *time.Time `json:"last_published,omitzero" model:"max=posts.published_at"`
	HasPosts      *bool      `json:"has_posts,omitzero" model:"exists=posts"`
}

Then pass the relationship and the column to WithSum, WithAvg, WithMin, or WithMax. To check whether any related models exist, pass the relationship to WithExists:

go
users, err := model.Query[models.User]().
	WithSum("posts", "votes").
	WithMax("posts", "published_at").
	WithExists("posts").
	Get(r)
if err != nil {
	return web.Fail(err)
}

for _, user := range users {
	if user.PostsVotes != nil {
		fmt.Println(user.Name, "has", *user.PostsVotes, "votes")
	}
}

Each function needs a field of a type that can hold its result. Pointer fields with omitzero stay nil and are left out of JSON responses when a query doesn't load them, and plain value types work as well. This table lists the field type for each tag, and the value that the field holds when the user has no posts:

TagFieldWithout related models
sum=posts.votesA pointer to an integer or float (or value type)nil, or 0 for a value type
avg=posts.votesA float, usually *float64nil
min=posts.votes, max=posts.votesThe column's type, usually a pointer to itnil, or the zero value
exists=posts*bool (or bool)false (non-nil for *bool)

Each aggregate runs one query, however many users there are. If the model has no field for an aggregate, Laravel panics and names the tag to add. To aggregate only some of the related rows, such as the votes on published posts, aggregate a filtered relationship, as in sum=published_posts.votes.

Loading into models you already have ​

Sometimes you already have a model, such as a user from the route, and then need its relationships. Pass the model to model.Load with the relationship names, which may be dotted names like the names you pass to With:

go
func Show(r *web.Request) *web.Response {
	user, err := model.FromRoute[models.User](r, "user")
	if err != nil {
		return web.Fail(err)
	}

	if err := model.Load(r, &user, "posts.comments", "profile"); err != nil {
		return web.Fail(err)
	}

	return web.JSON(user)
}

To load relationships into a slice of models, use model.LoadMany. Like With, it runs one query for each relationship, however many models the slice holds:

go
err := model.LoadMany(r, users, "posts", "profile")

To constrain the load, pass model.LoadQuery or model.LoadManyQuery a function that adds clauses to the related models' query, as you would pass WithQuery. For example, a profile page might show only the user's five most recent published posts:

go
err := model.LoadQuery(
	r,
	&user,
	"posts",
	func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereNotNull("published_at").Latest("published_at").Limit(5)
	},
)

As with WithQuery, a Limit in LoadManyQuery applies to each model's related models, so every user in the slice gets up to five posts.

Load and LoadMany run their queries every time and replace whatever the relationship fields already hold. If some of your models may already hold a relationship, use model.LoadMissing or model.LoadManyMissing instead. For example, a helper might prepare a feed of posts with their authors, while some of its callers already loaded the authors with With. LoadManyMissing loads authors only into the posts whose User field is nil, and runs no query when every post already holds its author:

go
func withAuthors(ctx context.Context, posts []models.Post) error {
	return model.LoadManyMissing(ctx, posts, "user")
}

A dotted name skips the relationships that are already loaded at each level. For example, model.LoadManyMissing(r, users, "posts.comments") loads posts into the users that don't hold them yet, then loads comments into every post that doesn't hold them, including the posts that were already loaded.

Loading counts and aggregates ​

You may also count related models or aggregate their columns for a model you already have. model.LoadCount sets the model's count field as WithCount does in a query, and model.LoadSum, LoadAvg, LoadMin, LoadMax, and LoadExists set the aggregate fields. For example, this handler shows a user from the route with their PostsCount and the total votes on their posts:

go
func Show(r *web.Request) *web.Response {
	user, err := model.FromRoute[models.User](r, "user")
	if err != nil {
		return web.Fail(err)
	}

	if err := model.LoadCount(r, &user, "posts"); err != nil {
		return web.Fail(err)
	}

	if err := model.LoadSum(r, &user, "posts", "votes"); err != nil {
		return web.Fail(err)
	}

	return web.JSON(user)
}

These functions load into one model at a time. When you read many models, add WithCount and the other aggregates to the query instead, so that one query counts the related models of every model.

Reading loaded relationships ​

Once a relationship is loaded, its field holds the related models, so you read them as you read any other field: post.User is a *User, and post.Comments is a []Comment that you may range over:

go
post, err := model.Query[models.Post]().With("user", "comments").FromRoute(r, "post")
if err != nil {
	return web.Fail(err)
}

fmt.Println(post.Title, "by", post.User.Name)

for _, comment := range post.Comments {
	fmt.Println(comment.Body)
}

A nil pointer or a nil slice means that the relationship wasn't loaded. Once a has_many or belongs_to_many relationship is loaded, its field holds a slice that isn't nil, even when there are no related models. A loaded belongs_to or has_one relationship with no related model stays nil. So when a relationship might not be loaded, or might have no related model, check the field before you read through it:

go
if post.Editor != nil {
	fmt.Println("Edited by", post.Editor.Name)
}

A count or an aggregate fills only its own field. For example, WithCount("comments") sets CommentsCount and leaves Comments nil, so LoadMissing still loads the comments. Likewise, because a loaded belongs_to or has_one relationship with no related model stays nil, LoadMissing and LoadManyMissing query for that relationship again.

警告

Reading through a relationship that wasn't loaded, such as post.User.Name after a query without With("user"), panics with a nil pointer dereference. Ranging over a has_many relationship that wasn't loaded doesn't panic, but finds no models, so a page that forgets With("comments") shows no comments rather than failing.

When a reader comments on a post, the new comment's post_id column must hold the post's ID. Rather than set the ID yourself, you may create the comment through the post's comments relationship. Pass model.CreateRelated the post, the relationship's name, and the comment, and Laravel sets post_id before it creates the comment, as model.Create would:

go
type StoreComment struct {
	Body string `json:"body"`
}

func (f *StoreComment) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Body, rule.Required, rule.Max(2000)),
	)
}

func Store(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	form, err := r.Validate[StoreComment]()
	if err != nil {
		return web.Fail(err)
	}

	comment := models.Comment{UserID: r.User[models.User]().ID, Body: form.Body}
	if err := model.CreateRelated(r, &post, "comments", &comment); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

Afterward, comment holds its new ID and its post_id. If the relationship names its own keys, such as foreign_key=author_email,local_key=email, Laravel sets those columns instead. model.CreateRelated works through has_one, has_many, morph_one, morph_many, and the relationships with join tables.

Through a belongs_to_many relationship, model.CreateRelated inserts the related model and the join row that links it in one transaction. For example, this code creates a tag and links it to the post. If inserting the join row fails, Laravel removes the new tag too:

go
tag := models.Tag{Name: "Go"}
if err := model.CreateRelated(r, &post, "tags", &tag); err != nil {
	return web.Fail(err)
}

To create several related models at once, pass a slice to model.CreateManyRelated. Like model.CreateMany, it creates every model in one transaction, so if one insert fails, Laravel creates none of them:

go
tags := []models.Tag{{Name: "Go"}, {Name: "Laravel"}}
if err := model.CreateManyRelated(r, &post, "tags", tags); err != nil {
	return web.Fail(err)
}

As with model.Create, each model you create through a relationship runs its Creating hook and dispatches its model.Created event.

A belongs_to relationship works the other way, because the foreign key is on the model you're writing. To set a post's author, pass the user to model.Associate. It sets the post's user_id to the user's ID and puts a copy of the user in the post's User field, so you may read post.User without another query. Then create the post as usual:

go
post := models.Post{Title: "Release notes"}
model.Associate(&post, "user", r.User[models.User]())

if err := model.Create(r, &post); err != nil {
	return web.Fail(err)
}

To move a post that already exists to another author, such as when an editor transfers it, associate the new author and save the post with model.Save:

go
model.Associate(&post, "user", &author)

if err := model.Save(r, &post); err != nil {
	return web.Fail(err)
}

Attaching and syncing join rows ​

Unlike a has_many relationship, whose foreign key lives on the related table, a belongs_to_many relationship stores its links in a join table, such as post_tag between posts and tags. Rather than insert and delete those rows yourself, you may attach, detach, sync, and toggle them with the functions in the model package. Each function takes a context, a pointer to the model, the relationship's name, and the related models or their IDs.

To link related models to a model, pass them (or their IDs) to model.Attach. For example, a tag picker that saves each click might add one tag to a post from a route such as /posts/{post}/tags/{tag}:

go
func AddTag(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	tag, err := model.FromRoute[models.Tag](r, "tag")
	if err != nil {
		return web.Fail(err)
	}

	if err := model.Attach(r, &post, "tags", tag); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

Attach takes any number of persisted models or IDs, as in model.Attach(r, &post, "tags", tag1, tag2) or model.Attach(r, &post, "tags", 1, 2). It inserts a join row even when the tag is already linked, and that insert fails on the join table's unique index. If some of the tags may already be linked, use Sync instead.

To remove links without deleting the related models themselves, pass the models or IDs to model.Detach. It returns the number of join rows it deleted:

go
removed, err := model.Detach(r, &post, "tags", tag)

When a form sends the complete set of related models that a model should have, such as the tags picked when the author edits a post, use model.Sync. It attaches the IDs that aren't linked yet and detaches the linked IDs that aren't in the list, in a transaction. To detach every tag, sync an empty list:

go
type PostTags struct {
	TagIDs []int64 `json:"tag_ids"`
}

func (f *PostTags) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.TagIDs, rule.Max(20), rule.Each(model.Exists[models.Tag]())),
	)
}

func UpdateTags(r *web.Request) *web.Response {
	post, err := model.FromRoute[models.Post](r, "post")
	if err != nil {
		return web.Fail(err)
	}

	form, err := r.Validate[PostTags]()
	if err != nil {
		return web.Fail(err)
	}

	if _, err := model.Sync(r, &post, "tags", form.TagIDs); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

If you'd like to flip the links of some related models, detaching the ones that are linked and attaching the ones that aren't, use model.Toggle:

go
_, err := model.Toggle(r, &post, "tags", []int64{tutorial.ID, release.ID})

Sync and Toggle return a model.Changes, whose Attached and Detached fields list the IDs that the call linked and unlinked. Its Updated field lists the already linked IDs whose join rows SyncWith wrote. For example, you might notify the followers of each newly added tag:

go
changes, err := model.Sync(r, &post, "tags", form.TagIDs)
if err != nil {
	return web.Fail(err)
}

if len(changes.Attached) > 0 {
	// Notify the followers of the new tags...
}

Writing join-row columns ​

A join table often holds more than the two keys. For example, a user may hold each role at a level, so role_user has a level column next to user_id and role_id. When an admin grants a user a role, the admin page also sets the level. model.AttachWith and model.SyncWith take a map from each related model's ID to the column values of its join row:

go
type GrantRole struct {
	RoleID int64  `json:"role_id"`
	Level  string `json:"level"`
}

func (f *GrantRole) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.RoleID, rule.Required, model.Exists[models.Role]()),
		rule.Field(&f.Level, rule.Required, rule.In("owner", "member")),
	)
}

func Grant(r *web.Request) *web.Response {
	user, err := model.FromRoute[models.User](r, "user")
	if err != nil {
		return web.Fail(err)
	}

	form, err := r.Validate[GrantRole]()
	if err != nil {
		return web.Fail(err)
	}

	err = model.AttachWith(r, &user, "roles", map[int64]db.Values{
		form.RoleID: {"level": form.Level},
	})
	if err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

SyncWith writes each ID's column values to the join rows it inserts and to the join rows it keeps. So a form that sends every role with its level both links the roles and updates their levels. Like Sync, SyncWith returns a model.Changes, and its Updated field lists the roles the user already held, whose levels it wrote. In this example, owner and editor are models.Role values:

go
changes, err := model.SyncWith(r, &user, "roles", map[int64]db.Values{
	owner.ID:  {"level": "owner"},
	editor.ID: {"level": "member"},
})
if err != nil {
	return web.Fail(err)
}

for _, roleID := range changes.Updated {
	// Record each level that was set in the audit log...
}

To change the columns of one join row without attaching or detaching anything, pass the related model (or its ID) and the new column values to model.UpdateJoinRow. If the user doesn't hold the role, UpdateJoinRow changes nothing:

go
err := model.UpdateJoinRow(r, &user, "roles", owner, db.Values{"level": "member"})

To create a new role and grant it in one step, so that a failed grant doesn't leave a role behind, wrap both writes in a transaction. Pass the transaction's ctx to each write:

go
err := db.Transaction(r, func(ctx context.Context) error {
	role := models.Role{Name: "Billing"}
	if err := model.Create(ctx, &role); err != nil {
		return err
	}

	return model.AttachWith(ctx, &user, "roles", map[int64]db.Values{
		role.ID: {"level": "owner"},
	})
})

The db.Values map may name any column of the join table. To read these columns back with the related models, and to have Laravel set the join row's created_at and updated_at columns, declare a join row.

Defining join-row models ​

Once a join row holds a user's level, the admin page will want to show each of the user's roles with that level. To read join-row columns along with the related models, declare two structs. The first struct has a field for each join-row column you use. The second struct is the relationship's element type, which embeds the related model and holds the join row in a field tagged model:"join":

go
// models/role.go
package models

import "time"

type Role struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

// Membership is a row of role_user: a user's level in a role.
type Membership struct {
	Level     string    `json:"level"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// UserRole is one of a user's roles, with its row of role_user.
type UserRole struct {
	Role
	Join Membership `json:"join" model:"join"`
}

The join row's fields map to columns as a model's fields do, so CreatedAt reads created_at. List only the columns you need. You may include the key columns, user_id and role_id, as fields too.

As on a model, CreatedAt and UpdatedAt fields turn on timestamps. When the relationship's write functions insert a join row, they set both columns, and when they change a join row, they set updated_at, unless you pass your own value for the column. A relationship whose field holds plain []Role declares no join row, so its writes leave these columns alone.

Then give the relationship field the element type. The relationship still reads the roles table, with role_user as its join table:

go
// models/user.go
type User struct {
	ID int64 `json:"id"`
	// ...

	Roles []UserRole `json:"roles,omitzero" model:"belongs_to_many"`
}

Accessing join-row attributes ​

When you load the relationship, Laravel reads each role's join row along with the role. Because a UserRole embeds a Role, you may read the role's fields directly, and read the join row from its Join field:

go
func Show(r *web.Request) *web.Response {
	user, err := model.Query[models.User]().With("roles").FromRoute(r, "user")
	if err != nil {
		return web.Fail(err)
	}

	for _, role := range user.Roles {
		fmt.Println(role.Name, "as", role.Join.Level)
	}

	return web.JSON(user)
}

To pass a role to a function that takes a models.Role, or to a write such as model.Update, pass role.Role.

Querying join rows directly ​

Sometimes you want a user's roles with their join rows without loading the roles into the user, such as to show one page of a long list. Pass the element type to model.Related. For example, this query paginates the user's roles 15 at a time, ordered by when each membership was created, and returns each role with its Membership:

go
roles, err := model.Related[models.UserRole](&user, "roles").
	Latest("role_user.created_at").
	Paginate(r, r.Page(15))

The query reads the roles table, but its read methods, such as Get, First, Find, ChunkByID, and the paginators, return UserRole values. Find reads one linked role with its join row by the role's ID, and returns a *db.NotFoundError when the user doesn't hold that role:

go
role, err := model.Related[models.UserRole](&user, "roles").Find(r, 2)

This works on every belongs_to_many relationship, including one whose field holds plain []Role. So if only a few pages need the join rows, the relationship field may stay []Role, and model.Related[models.Role] reads plain roles.

Filtering and ordering by join-row columns ​

Sometimes you need only the related models whose join rows match a condition, such as the roles a user owns. A query of a belongs_to_many relationship joins the join table, so you may use the join table's columns in clauses when you prefix them with the table's name, as in role_user.level. This works in model.Related queries and in the functions you pass to WithQuery, WithCountQuery, WhereHas, and WhereDoesntHave. For example, this query loads each user's owner roles, newest first:

go
users, err := model.Query[models.User]().
	WithQuery("roles", func(q *model.Builder[models.UserRole]) *model.Builder[models.UserRole] {
		return q.WhereEq("role_user.level", "owner").Latest("role_user.created_at")
	}).
	Get(r)

To find the users who own any role, filter WhereHas by the join table's column:

go
owners, err := model.Query[models.User]().
	WhereHas("roles", func(q *model.Builder[models.Role]) *model.Builder[models.Role] {
		return q.WhereEq("role_user.level", "owner")
	}).
	Get(r)

To check one user's level without loading their roles, such as in an ability that queries the database, filter the relationship's query and call Exists. This query checks whether the user owns the billing role:

go
isOwner, err := model.Related[models.Role](&user, "roles").
	WhereEq("name", "billing").
	WhereEq("role_user.level", "owner").
	Exists(r)

Laravel reads a column name without a table prefix as a column of the related model, and checks the name against the model's fields. Laravel doesn't check the names of join-table columns, so a misspelled join-table column fails when the database runs the query.

Polymorphic relationships ​

Sometimes one kind of model belongs to more than one kind of parent. For example, your application might let users comment on both blog posts and videos. Rather than keep a separate comments table for each kind of parent, a polymorphic relationship keeps every comment in one comments table. Each row records which kind of model the comment belongs to, and the key of that model.

The comments table holds a type column and a key column for the parent. In the table's migration, the schema builder's Morphs method adds both columns and an index on the pair:

go
// database/migrations/2026_11_13_090000_create_comments_table.go
package migrations

import (
	"context"

	"go.laravel.com/schema"
)

func createCommentsTable(ctx context.Context) error {
	return schema.Create(ctx, "comments", func(table *schema.Blueprint) {
		table.ID()
		table.Text("body")
		table.Morphs("commentable")
		table.Timestamps()
	})
}

Morphs("commentable") adds commentable_type, a string, and commentable_id, a big integer. Use UUIDMorphs or ULIDMorphs when the parents have UUID or ULID keys, and the Nullable forms when a row may belong to nothing.

Declaring polymorphic relationships ​

A comment's parent may be a post or a video, so the comment's relationship field holds an interface that both *Post and *Video implement. Declare the interface beside the Comment model, give the interface an unexported method, and tag the field model:"morph_to":

go
// models/comment.go
package models

import "time"

// Commentable is a model that users comment on: a *Post or a *Video.
type Commentable interface{ commentable() }

type Comment struct {
	ID              int64     `json:"id"`
	Body            string    `json:"body"`
	CommentableType string    `json:"commentable_type"`
	CommentableID   int64     `json:"commentable_id"`
	CreatedAt       time.Time `json:"created_at"`
	UpdatedAt       time.Time `json:"updated_at"`

	Commentable Commentable `json:"commentable,omitzero" model:"morph_to"`
}

Then give each parent model the interface's method. With that method in place, the compiler rejects any other model that you try to set as a comment's parent:

go
// models/post.go
func (*Post) commentable() {}
go
// models/video.go
func (*Video) commentable() {}

A morph_to field reads the two columns named after the field, so Commentable reads commentable_type and commentable_id. If those columns are nullable, make both column fields pointers, *string and *int64.

The type column stores each model's morph name. By default, a model's morph name is its type's name in snake case, so a comment on a Post stores post and a comment on a BlogPost stores blog_post. Renaming a Go type therefore changes the name its rows need. To keep a name that rows already hold, such as after you rename Clip to Video, give the model a MorphName method:

go
// models/video.go
func (Video) MorphName() string { return "clip" }

Go can't list the types that implement an interface, so you list every model that a type column may name in the Morphs field of your application's options, in bootstrap/app.go. Each morph_to relationship reads the models in Morphs that implement its interface:

go
// bootstrap/app.go
return laravel.Options{
	// ...
	Morphs: []any{models.Post{}, models.Video{}},
}

If a row's type column holds a name that no model in Morphs uses, reading that row fails with an error.

Next, declare the other side of the relationship on each parent. A morph_many field's name option names the morph_to relationship on the related model, so name=commentable refers to Comment's Commentable field:

go
// models/post.go
type Post struct {
	ID    int64  `json:"id"`
	Title string `json:"title"`

	Comments []Comment `json:"comments,omitzero" model:"morph_many,name=commentable"`
	Image    *Image    `json:"image,omitzero" model:"morph_one,name=imageable"`
}

A morph_one relationship follows the same pattern as morph_many when a parent has at most one related row, such as a post's cover image. In this example, Image has ImageableType and ImageableID fields and a morph_to field named Imageable, as Comment has Commentable.

You may use morph_many and morph_one relationships with With, Has, WhereHas, WithCount, model.Related, and model.CreateRelated, as you would has_many and has_one relationships. They read only the rows whose type column holds the parent's morph name, so a video's comments never show up under the post with the same ID:

go
post, err := model.Query[models.Post]().With("comments", "image").FromRoute(r, "post")
if err != nil {
	return web.Fail(err)
}

recent, err := model.Related[models.Comment](&post, "comments").Latest("created_at").Limit(10).Get(r)

On a morph_one relationship, you may also use of_many to pick a single standout record, such as a post's latest image:

go
LatestImage *Image `json:"latest_image,omitzero" model:"morph_one,name=imageable,of_many=latest"`

Loading polymorphic relationships ​

You load a morph_to relationship with With, as you load a belongs_to relationship. For example, a page of recent comments might show the title of the post or the name of the video under each comment. Because the Commentable field holds a pointer to either kind of parent, use a type switch to reach the model:

go
func Index(r *web.Request) *web.Response {
	comments, err := model.Query[models.Comment]().
		With("commentable").
		Latest("created_at").
		Limit(50).
		Get(r)
	if err != nil {
		return web.Fail(err)
	}

	for _, comment := range comments {
		switch parent := comment.Commentable.(type) {
		case *models.Post:
			fmt.Println(comment.Body, "on", parent.Title)
		case *models.Video:
			fmt.Println(comment.Body, "on", parent.Name)
		}
	}

	return web.JSON(comments)
}

Laravel runs one query for each type that the comments refer to, so loading 50 comments on posts and videos takes three queries. If a comment's parent has been deleted, the comment loads a nil Commentable.

Each kind of parent has relationships of its own, such as a post's author or a video's channel. To load those relationships, call WithQuery once for each parent model whose relationships you need. Laravel runs each function only on the query for that function's model. This query loads every comment with its parent, along with each post's author and each video's channel and tags:

go
comments, err := model.Query[models.Comment]().
	WithQuery("commentable", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.With("user")
	}).
	WithQuery("commentable", func(q *model.Builder[models.Video]) *model.Builder[models.Video] {
		return q.With("channel", "tags")
	}).
	Get(r)

A dotted name can't go past a morph_to relationship, because each kind of parent has different relationships. So With("commentable.user") panics and points you to WithQuery.

You may also load a morph_to relationship into comments you already have with model.Load, model.LoadMany, and model.LoadManyMissing. To find one comment's parent without loading it into the comment, pass the comment's type and key columns to model.FindMorph:

go
parent, err := model.FindMorph[models.Commentable](r, comment.CommentableType, comment.CommentableID)

A morph_to relationship refers to one model, so WithCount("commentable") panics. To check whether a comment's parent exists, filter with Has instead.

Filtering by the model a relationship refers to ​

You may filter by a morph_to relationship as you filter by other relationships. Has("commentable") keeps the comments whose parent still exists, and DoesntHave("commentable") keeps the comments whose parent doesn't. To filter by the parent's columns, pass WhereHas a function that takes one parent model's builder. WhereHas then keeps only the comments on that kind of model. For example, this query finds the comments on posts whose titles mention Go, and skips every comment on a video:

go
aboutGo, err := model.Query[models.Comment]().
	WhereHas("commentable", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereLike("title", "%Go%", false)
	}).
	Get(r)

To match more than one kind of parent in one query, join a second WhereHas with OrWhereHas. For example, this query finds the comments on posts whose titles mention Go and the comments on videos whose names mention Go:

go
aboutGo, err := model.Query[models.Comment]().
	WhereHas("commentable", func(q *model.Builder[models.Post]) *model.Builder[models.Post] {
		return q.WhereLike("title", "%Go%", false)
	}).
	OrWhereHas("commentable", func(q *model.Builder[models.Video]) *model.Builder[models.Video] {
		return q.WhereLike("name", "%Go%", false)
	}).
	Get(r)

To find the comments on one model you already have, pass the parent to WhereBelongsTo. It compares both the type column and the key column, so a video with the post's ID doesn't match:

go
comments, err := model.Query[models.Comment]().WhereBelongsTo("commentable", &post).Get(r)

model.Related[models.Comment](&post, "comments") reads the same rows from the parent's side.

To filter by the kind of parent without a model in hand, compare the type column with the morph name that model.MorphName returns. This query finds every comment on a video:

go
onVideos, err := model.Query[models.Comment]().
	WhereEq("commentable_type", model.MorphName[models.Video]()).
	Get(r)

Writing polymorphic relationships ​

When you create a comment through its parent's relationship, Laravel sets both the type column and the key column. For example, this code creates a comment on a post:

go
comment := models.Comment{Body: form.Body}
if err := model.CreateRelated(r, &post, "comments", &comment); err != nil {
	return web.Fail(err)
}

To set the parent directly, pass any model that implements the interface to model.Associate. It sets the type and key columns and puts a copy of the parent in the Commentable field, so reading comment.Commentable afterward runs no query:

go
comment := models.Comment{Body: "Great video!"}
model.Associate(&comment, "commentable", &video)

if err := model.Create(r, &comment); err != nil {
	return web.Fail(err)
}

To move a comment to another parent, associate the new parent and then save the comment with model.Save(r, &comment).

Sometimes a form names the parent. For example, an image's edit form might let the user pick the post or user that owns the image from a list. Take the parent's type and key as form fields, and find the parent with model.FindMorph. Its type argument is the morph_to relationship's interface, and it only finds models in Morphs that implement that interface:

go
type ImageOwner struct {
	ImageableType string `json:"imageable_type"`
	ImageableID   int64  `json:"imageable_id"`
}

func (f *ImageOwner) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.ImageableType, rule.Required, rule.In("post", "user")),
		rule.Field(&f.ImageableID, rule.Required),
	)
}

func UpdateOwner(r *web.Request) *web.Response {
	image, err := model.FromRoute[models.Image](r, "image")
	if err != nil {
		return web.Fail(err)
	}

	form, err := r.Validate[ImageOwner]()
	if err != nil {
		return web.Fail(err)
	}

	owner, err := model.FindMorph[models.Imageable](r, form.ImageableType, form.ImageableID)
	if err != nil {
		return web.Fail(err)
	}

	model.Associate(&image, "imageable", owner)

	if err := model.Save(r, &image); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}

If the type names none of the interface's models, or no row of that model has the key, FindMorph returns a *db.NotFoundError. Passing that error to web.Fail responds with a 404.

Many-to-many polymorphic relationships ​

Tags are a common use of a polymorphic many-to-many relationship. For example, a post may have many tags and a video may have many tags, while each tag may be on many posts and many videos. One taggables join table holds every link. Each row holds the tag's key, along with the type and key of the model that the tag is on:

go
func createTaggablesTable(ctx context.Context) error {
	return schema.Create(ctx, "taggables", func(table *schema.Blueprint) {
		table.ForeignID("tag_id").Constrained().CascadeOnDelete()
		table.Morphs("taggable")

		table.Unique("tag_id", "taggable_type", "taggable_id")
	})
}

Each model that can be tagged declares a morph_to_many relationship, and the Tag model declares one morphed_by_many relationship for each type that it tags. The name option is the prefix of the join table's type and key columns, so name=taggable reads taggable_type and taggable_id:

go
// models/post.go
Tags []Tag `json:"tags,omitzero" model:"morph_to_many,name=taggable"`
go
// models/tag.go
type Tag struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`

	Posts  []Post  `json:"posts,omitzero" model:"morphed_by_many,name=taggable"`
	Videos []Video `json:"videos,omitzero" model:"morphed_by_many,name=taggable"`
}

By default, the join table's name is name made plural, so taggable becomes taggables. The tag's column is the tag model's name in snake case followed by _id, so Tag reads tag_id. If your table or column has another name, set table, and set related_column on morph_to_many or parent_column on morphed_by_many. Each side of these relationships names its model types in its field, so they need no interface and no entry in Morphs.

These relationships work as belongs_to_many relationships do, including an element type that holds the join row. They read only the join rows that hold the model's morph name. model.Attach, Detach, Sync, Toggle, UpdateJoinRow, and CreateRelated write the taggable_type column for you, so syncing a post's tags never touches a video's tags:

go
if _, err := model.Sync(r, &post, "tags", form.TagIDs); err != nil {
	return web.Fail(err)
}

if err := model.Attach(r, &video, "tags", tag.ID); err != nil {
	return web.Fail(err)
}

Serializing relationships ​

When you return a model as JSON, such as with web.JSON or in Inertia props, each loaded relationship encodes under its field's json name. So a page gets the related models without a response struct of its own. Because an unloaded relationship is nil, omitzero in the json tag leaves it out, and the response contains only the relationships you loaded:

go
func Show(r *web.Request) *web.Response {
	user, err := model.Query[models.User]().With("posts").FromRoute(r, "user")
	if err != nil {
		return web.Fail(err)
	}

	return web.JSON(user)
}

That handler returns the user along with their loaded posts array. A loaded relationship with no models encodes as []:

json
{
	"id": 1,
	"name": "Taylor",
	"posts": [
		{
			"id": 1,
			"user_id": 1,
			"title": "Hello"
		}
	]
}

A loaded belongs_to or has_one relationship with no related model is nil too, so omitzero leaves it out as well. Without omitzero, every unloaded relationship encodes as null. Related models follow the same serialization rules as the model you return, so a related model's fields tagged json:"-" stay on the server.

Serializing aggregates ​

A count or an aggregate encodes under its field's json name, such as comments_count or posts_votes, alongside the model's columns:

json
{
	"id": 1,
	"title": "Hello",
	"comments_count": 3
}

Because pointer fields such as *int and *bool stay nil until a query loads them, omitzero leaves unloaded counts and aggregates out of JSON responses. A loaded count of zero still encodes as "comments_count": 0, and a loaded existence check with no related models still encodes as "has_posts": false. If you declare an aggregate as a plain int or bool instead, queries that don't load it still send 0 or false to the client, and adding omitzero would omit loaded zero and false values too.

Serializing join rows ​

When a relationship's element type holds a join row, each related model encodes with its join row nested under the join row field's json name, such as join:

json
{
	"id": 1,
	"name": "Taylor",
	"roles": [
		{
			"id": 2,
			"name": "admin",
			"join": {
				"level": "owner",
				"created_at": "2026-11-10T09:00:00Z",
				"updated_at": "2026-11-10T09:00:00Z"
			}
		}
	]
}

Serializing polymorphic relationships ​

A loaded morph_to relationship encodes as the model it holds, without a field that names the model's type. To tell which kind of model the parent is, read the comment's type column, such as "commentable_type": "clip" for a video:

json
{
	"id": 4,
	"body": "Great video!",
	"commentable_type": "clip",
	"commentable_id": 1,
	"commentable": {
		"id": 1,
		"name": "Intro"
	}
}