我想存储其输入字段可由用户编辑的Web表单的数据。输入字段可以采用字符串或整数数据(为简化起见),并且可以为任意数字。为此,我创建了以下结构:
class Post {
public Id!: number;
public FieldValues?: FieldValue[];
public static associations: {
FieldValues: Association<Post, FieldValue>
};
}
interface FieldValue{
public Id!: number;
PostId: number;
}
class StringData implements FieldValue{
public Id!: number;
public PostId: number;
public Value!: string;
}
class IntegerData implements FieldValue{
public Id!: number;
public PostId: number;
public Value!: number;
}
Post.init({...},
{
tableName: "Posts"
}
)
StringData.init({...},
{
tableName: "StringData"
}
)
IntegerData.init({...},
{
tableName: "IntegerData"
}
)
Post.hasMany(FieldValue, { // breaks
sourceKey: "Id",
foreignKey: "FieldId",
as: "FieldValues"
})
StringData.belongsTo(Post, {
foreignKey: "FieldId"
})
IntegerData.belongsTo(Post, {
foreignKey: "FieldId"
})
显然我不能在关联中使用接口或抽象类。我想要实现的是:
const post = await Post.create()
const stringData = await StringData.create({ Value: "test string", PostId: post.Id })
const integerData = await IntegerData.create({ Value: 123, PostId: post.Id })
const _post = await Post.findByPk(post.id, {
include: [Post.associations.FieldValues],
})
_post.FieldValues = ["test string", 123] // expected output
任何帮助将不胜感激。