Skip to content

Has One 关联

介绍

Has One 关联表示一个模型拥有另一个模型的单个实例。这是一种一对一的关联关系,通常用于将一个表的数据扩展到另一个表中。

定义 Has One 关联

使用 @HasOne 装饰器来定义一对一关联:

ts
import { Table, Field, FieldType, Model, HasOne } from '@ibestservices/ibest-orm';

@Table({ name: 'users' })
class User extends Model {
  @Field({ type: FieldType.TEXT, tag: ['notNull'] })
  name?: string;

  @Field({ type: FieldType.TEXT })
  email?: string;

  @HasOne({
    target: () => UserProfile,
    foreignKey: 'user_id',
    localKey: 'id'
  })
  profile?: UserProfile;

  constructor(name: string, email: string) {
    super();
    this.name = name;
    this.email = email;
  }
}

@Table({ name: 'user_profiles' })
class UserProfile extends Model {
  @Field({ type: FieldType.INTEGER, tag: ['notNull'] })
  user_id?: number;

  @Field({ type: FieldType.TEXT })
  avatar?: string;

  @Field({ type: FieldType.TEXT })
  bio?: string;

  constructor(user_id: number, avatar: string, bio: string) {
    super();
    this.user_id = user_id;
    this.avatar = avatar;
    this.bio = bio;
  }
}

配置参数

target

  • 类型: () => Class
  • 描述: 目标模型类的工厂函数
  • 必需: 是

foreignKey

  • 类型: string
  • 描述: 目标表中的外键字段名
  • 默认值: ${当前表名}_id
  • 示例: 'user_id'

localKey

  • 类型: string
  • 描述: 当前表中的本地键字段名(通常是主键)
  • 默认值: 'id'
  • 示例: 'id'

查询 Has One 关联

预加载关联数据

ts
// 查询用户及其档案信息
const userWithProfile = await this.orm.Session(User)
  .With('profile')
  .Where('id', 1)
  .FirstWithRelations();

console.log('用户信息:', userWithProfile);
// 输出:
// {
//   id: 1,
//   name: "张三",
//   email: "zhangsan@example.com",
//   profile: {
//     id: 1,
//     user_id: 1,
//     avatar: "avatar1.jpg",
//     bio: "热爱技术的程序员"
//   }
// }

查询多个用户的关联数据

ts
// 查询所有用户及其档案
const usersWithProfiles = await this.orm.Session(User)
  .With('profile')
  .FindWithRelations();

usersWithProfiles.forEach(user => {
  console.log(`用户 ${user.name} 的头像: ${user.profile?.avatar}`);
});

注意事项

提示

  • Has One 关联通过外键建立关系,确保外键字段存在
  • 预加载查询会执行两次 SQL 查询:先查主表,再查关联表
  • 关联数据为 null 时表示没有对应的关联记录

注意

  • 外键字段应该有适当的索引以提高查询性能
  • 删除主记录时要考虑关联数据的处理
  • 一对一关联中,关联表的外键应该是唯一的