简体   繁体   中英

Sequelize - do I have to specify "as" in both model and query?

This seems redundant, and forces me to hard-code the same string in two spots - or stick it in a variable that has to be passed around. Either way, if I specify the "as" of a relationship in my model, why do I have to call it later with the same "as" property when querying?

My relationship:

organization.hasMany(client, { as: "Clients", foreignKey: "organization_id" });
client.belongsTo(organization, { as: "AuthOrganization", foreignKey: "organization_id" });

Query:

    let data = await client.findOne({
        include: [{ model: organization, as: "AuthOrganization" }]
    }, { raw: true });

If I omit the same "as" property, an error is thrown telling me to put it in there. I'm new to Sequelize, but it appears to be this way because "as" can be used to identify relationships where it's ambiguous. However, seems like a reasonable default would be the value you set in the model, no?

What I really want is this, when I write a query:

    let data = await client.findOne({
        include: organization
    }, { raw: true });

I'm only doing this to avoid the automatic underscore in the mixin function names. I couldn't stomach the fugly "addAuth_organization" function name, and I couldn't find another way around this issue, either.

I'll take that as a "yes".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM