Skip to main content

Using Associations

Finding Records with Associations

To load associated records, use the include parameter. This parameter accepts a callback that gives you access to an "Include Builder" for the model.

Basic Syntax

Use the generated methods on the include builder (like .post() or .posts()) to include associations.

// Single association
final user = await User.model.findOne(
where: User.model.id.equals(1),
include: (u) => [
u.post(), // Includes the 'post' association
],
);

// Multiple associations
final user = await User.model.findOne(
where: User.model.id.equals(1),
include: (u) => [
u.post(),
u.posts(),
],
);

Note: These methods (like u.post) are generated based on your association definitions (e.g., @HasOne(..., as: 'post')). If an association is not defined in the model, the method will not be available.

Filtering Included Records

You can filter associated records by passing options to the include method.

final user = await User.model.findOne(
where: User.model.id.equals(1),
include: (u) => [
// Include the 'post' association where post.id is 1
u.post(
where: (p) => p.id.eq(1),
),
],
);

Using IncludeBuilder

For more dynamic or complex scenarios, you can manually create an IncludeBuilder:

// Manually create an include builder for the 'post' association
var postInclude = IncludeBuilder<PostModel>(association: 'post');


final user = await User.model.findOne(
include: (u) => [
// Use the manual builder
postInclude.copyWith(
where: (p) => p.title.like('%News%'),
),
],
);

Nested Associations

You can nest includes to load deep relationships (associations of associations).

// User -> Posts -> Comments
final user = await User.model.findOne(
where: User.model.id.equals(1),
include: (u) => [
u.posts(
include: (p) => [
p.comments(), // Assuming Post has @HasMany(Comment)
],
),
],
);