我有一个模型,可以使用node和sequalize将人们返回给我。该模型看起来像这样
class DbModel implements IModelMaker {
static _model: IDatabaseModel = null;
getModel(db: ISequelize): IDatabaseModel {
if (DbModel._model)
return DbModel._model;
const options = helper.getDatabaseDefaultOptions('people');
const entity: any = {};
entity['people_id'] = {type: Sequelize.UUID, primaryKey: true, 'defaultValue': Sequelize.UUIDV4};
entity['sexes_id'] = helper.getForeignKey('sexes_id', sexes.getModel(db));
entity['marital_states_id'] = helper.getForeignKey('marital_states_id', marital_states.getModel(db));
entity['employment_states_id'] = helper.getForeignKey('employment_states_id', employment_states.getModel(db));
entity['linkedins_id'] = helper.getForeignKey('linkedins_id', linkedins.getModel(db));
entity['facebooks_id'] = helper.getForeignKey('facebooks_id', facebooks.getModel(db));
entity['first_names'] = Sequelize.TEXT;
entity['surnames'] = Sequelize.TEXT;
entity['name_to_call_user'] = Sequelize.TEXT;
entity['id_number'] = Sequelize.TEXT;
entity['passport_number'] = Sequelize.TEXT;
entity['birth_date'] = Sequelize.DATEONLY;
entity['tax_number'] = Sequelize.TEXT;
entity['vat_number'] = Sequelize.TEXT;
entity['message_to_show_on_user_invoice'] = Sequelize.TEXT;
entity['workplace_name'] = Sequelize.TEXT;
entity['is_verified'] = Sequelize.BOOLEAN;
entity['has_private_profile_enabled'] = Sequelize.BOOLEAN;
entity['mobile_phone'] = Sequelize.TEXT;
entity['occupations_id'] = Sequelize.UUID;
entity['profile_photo_url'] = Sequelize.TEXT;
entity['private_profile_url'] = Sequelize.TEXT;
entity['public_profile_url'] = Sequelize.TEXT;
entity['description'] = Sequelize.TEXT;
entity['created_at'] = Sequelize.DATE;
const result = db.define('dbo.people', entity, options);
result.belongsTo(sexes.getModel(db), {foreignKey: 'sexes_id'});
result.belongsTo(marital_states.getModel(db), {foreignKey: 'marital_states_id'});
result.belongsTo(employment_states.getModel(db), {foreignKey: 'employment_states_id'});
result.belongsTo(linkedins.getModel(db), {foreignKey: 'linkedins_id'});
result.belongsTo(facebooks.getModel(db), {foreignKey: 'facebooks_id'});
DbModel._model = result;
return result;
}
这让我获得了存储在dbo.people表中的结果,这很棒,因为这就是我想要的,这个模型非常适用于此。
现在我想要做的是添加到这个模型并从另一个表调用数据。所以我希望使用此模型调用dbo.users_references
中的数据。
我的问题是,有没有办法将连接语句添加到像上面那样创建的模型中,或者我需要创建一个新模型并将其作为单独的函数调用。第二种方式适用于我的情况,但我希望保持简单,所以如果我能在一个模型中得到它,那么我会很高兴,否则我必须对其他选项感到温和。
答案 0 :(得分:1)
您需要define
users_references
的模型,并以与sexes
,marital_states
等相同的方式关联它。实际上,联接将是在指定include
的内容时,在查询时发生。
用法示例:
DbModel.findAll({
where: ...,
include: [
{ model: employment_states.getModel(db) },
{ model: users_references.getModel(db) }
]
});
我道歉,如果这看起来有点波动 - 那就是,因为我收集了你的项目中有很多辅助逻辑,而不是在帖子中。您可能想要查看the docs,但不可否认的是,他们对如何从查询中的相关表格实际获取数据有点模糊,但它们应该足以涵盖您所描述的内容。