() => PostPost — so two models can point at each other across importsundefined at load time.import {
DataTypes, Model, Table, Column, PrimaryKey, AutoIncrement,
HasMany, BelongsTo, HasOne, BelongsToMany,
} from 'ts-prorm-orm';
@Table({ tableName: 'users' })
class User extends Model {
@Column(DataTypes.INTEGER())
@PrimaryKey
@AutoIncrement
declare id: number;
@Column(DataTypes.STRING(100))
declare name: string;
@HasMany(() => Post, { foreignKey: 'userId', as: 'posts' })
declare posts?: Post[];
@HasOne(() => Profile, { foreignKey: 'userId', as: 'profile' })
declare profile?: Profile;
}
@Table({ tableName: 'posts' })
class Post extends Model {
@Column(DataTypes.INTEGER())
@PrimaryKey
@AutoIncrement
declare id: number;
@Column(DataTypes.STRING(200))
declare title: string;
@Column(DataTypes.INTEGER())
declare userId: number;
@BelongsTo(() => User, { foreignKey: 'userId', as: 'author' })
declare author?: User;
@BelongsToMany(() => Tag, { through: 'post_tags', foreignKey: 'postId', otherKey: 'tagId', as: 'tags' })
declare tags?: Tag[];
}const Users = prorm.addModel(User);
const Posts = prorm.addModel(Post);
const Tags = prorm.addModel(Tag);
await prorm.sync();Post before Userdefine(), and theProfile and Tag as plain id + one column models, sync() createsthrough: 'post_tags':Post getsgetAuthor, setAuthor, unsetAuthor, createAuthor, hasAuthor,countAuthor from @BelongsTo, and getTags, addTag, addTags,removeTag, setTags, countTags, hasTag from @BelongsToMany:const post = await Posts.findByPk(1);
const math = await Tags.create({ name: 'math' });
await post.addTag(math); // INSERT INTO "post_tags" ("postId", "tagId") VALUES (1, 1)
await post.getTags(); // [{ id: 1, name: 'math', … }]const users = await Users.findAll({
include: [
{ model: Posts, as: 'posts' },
{ model: Profiles, as: 'profile' },
],
});
users[0].posts?.forEach((post) => console.log(post.title));
users[0].profile?.bio;const posts = await Posts.findAll({ include: [{ model: Tags, as: 'tags' }] });as in the include must match the as on the decorator — that name is howUser has no association to Post aliased 'articles'. Available: postsclass Post extends Model {
@BelongsTo(() => User, {
foreignKey: 'userId',
as: 'author',
onDelete: 'CASCADE',
onUpdate: 'RESTRICT',
})
declare author?: User;
}sync() puts the actions on the foreign key. On PostgreSQL:[!IMPORTANT]
When both sides declare the key (@HasManyonUserand@BelongsToonPost), the association registered first sets the reference, so put the
actions on both when you are not sure which that is. Before 4.9.2 neitheronDeletenoronUpdatereached the table; see
Foreign keys and constraints
for tables created by an older release.
posts?: Post[]) — it is only populated wheninclude it. Under strict, that forces the check at every use, which isNonAttribute as well so it stays out of