Skip to main content

hasOne

The hasOne association creates a one-to-one relationship where one instance of the source model belongs to one instance of the target model.

Basic Example

(tableName: 'users')
class User {
()
()
DataType id = DataType.INTEGER;

(Post, foreignKey: 'userId', as: 'post')
Post? post;

static UserModel get model => UserModel();
}

(tableName: 'posts')
class Post {
()
()
DataType id = DataType.INTEGER;

('user_id')
DataType userId = DataType.INTEGER;

DataType title = DataType.STRING;

static PostModel get model => PostModel();
}

Usage

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

print('User ID: ${user?.id}');
print('Post: ${user?.post?.title}');