How should the alias of sequelize association query be defined?

want to get such a sql statement through sequelize

I"ve tried a lot of ways to get a demo, but I"ve been reporting all kinds of errors

.
May.19,2022

I seem to have solved your problem:

  • Model definition:
// 
module.exports = app => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const User = app.model.define('user',{
        uid: { type: INTEGER, primaryKey: true, autoIncrement: true },
        name:{type:STRING(32),allowNull: true},
        avatar_url: STRING(255),
        password: STRING(64),
        email: STRING(64),
        phone: {type:STRING(32),allowNull: true},
        // created_at: DATE,
        // updated_at: DATE,
    });
    User.associate = function() {
        app.model.User.hasMany(app.model.Contacts,{foreignKey:"uid"});
        app.model.User.hasMany(app.model.Contacts,{foreignKey:"fid"});
    }
    return User;
}
// 
module.exports = app => {
    const { STRING, INTEGER, DATE } = app.Sequelize;
    const Contacts = app.model.define('contacts',{
        id: { type: INTEGER, primaryKey: true, autoIncrement: true },
        uid: {type:INTEGER,allowNull: true},
        fid: {type:INTEGER,allowNull: true},
        remarks: STRING,
        relation: {type:INTEGER,defaultValue:0},
        // created_at: DATE,
        // updated_at: DATE,
    });
    Contacts.associate = function() {
        app.model.Contacts.belongsTo(app.model.User,{foreignKey:"uid",as:'userInfo'});
        app.model.Contacts.belongsTo(app.model.User,{foreignKey:"fid",as:'contactInfo'});
    }
    return Contacts;
}
  • data query
const list =await this.ctx.model.Contacts.findAll({
    where:{
        uid
    },
    include: [
              {
                model: this.app.model.User,
                as:'contactInfo',
                attributes: ['uid', 'name', 'avatar_url', 'email', 'phone']
              }
    ]
});
  • return data

clipboard.png

Menu