代码之家  ›  专栏  ›  技术社区  ›  Charlie Fish

Sequelize填充关系查询任一表

  •  1
  • Charlie Fish  · 技术社区  · 7 年前

    我在Sequelize中有以下两个表

    const Tokens = sequelize.define("Tokens", {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        active: {
            type: DataTypes.BOOLEAN
        }
    });
    

    const User = sequelize.define("Users", {
        id: {
            type: DataTypes.UUID,
            defaultValue: DataTypes.UUIDV4,
            primaryKey: true
        },
        first_name: {
            type: DataTypes.STRING
        }
    });
    
    User.associate = models => {
        models["Users"].hasMany(models["Tokens"], {foreignKey: 'userID', as: 'tokens_userid'});
    };
    

    我正在尝试在Sequelize中运行以下查询。

    const token = await db.Tokens.findOne({
        where: {
            id,
            active: true
        },
        include: ["tokens_userid"]
    });
    

    但我得到了以下错误。

    Error: Association with alias "tokens_userid" does not exists
    

    我的主要目标是根据令牌ID获取用户。现在,我只想将该关联移动到用户表,但稍后的问题是,我想获取给定用户ID的所有令牌。因此,无论哪种方式,我都会遇到这个问题。

    我尝试添加以下行,但它是在抱怨循环关系或类似的东西。

    models["Tokens"].hasOne(models["User"], {foreignKey: 'userID', as: 'tokens_userid'});
    

    如何查询Users或Tokens表,并使其正确填充关系?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Charlie Fish    7 年前

    我可以通过在表中添加以下行来解决此问题。

    models["Tokens"].belongsTo(models["User"], {foreignKey: 'userID', as: 'tokens_userid_from_token'});
    

    基本上是我以前试过但改变了 hasOne belongsTo

    希望这能帮助其他人。

    推荐文章