Sequelizejs除了关联表的对象外还返回ID

时间:2018-12-24 21:11:12

标签: node.js sequelize.js

class User extends Sequelize.Model {
    static init(sequelize, DataTypes) {
        return super.init(
            {
                id: {type: DataTypes.INTEGER(11), allowNull: false, autoIncrement: true, primaryKey: true},
                cityId: {
                    type: DataTypes.INTEGER(11).UNSIGNED,
                    field: 'city_id',
                    references: {
                        model: City,
                        key: 'city_id'
                    },
                    allowNull: false, defaultValue: 0
                }
            },
            {
                tableName: "users",
                timestamps: false,
                sequelize
            }
        );
    }

    static getByIdWithCity(id) {
        return this.findOne({
            where: {
                id: {
                    [Op.eq]: id
                }
            },
            include: [{model: City}],
            raw: false
        });
    }
}

class City extends Sequelize.Model {
    static init(sequelize, DataTypes) {
        return super.init(
            {
                cityId: {type: DataTypes.INTEGER(11).UNSIGNED, allowNull: false, autoIncrement: true, primaryKey: true, field: 'city_id'},
                countryId: {type: DataTypes.INTEGER(11).UNSIGNED, allowNull: false, default: 0, field: 'country_id'}
            },
            {
                tableName: "city",
                timestamps: false,
                sequelize
            }
        );
    }
}

User.belongsTo(City, {foreignKey: 'cityId', targetKey: 'cityId'});
City.hasOne(User, {foreignKey: 'cityId', sourceKey: 'cityId'});

getByIdWithCity返回:

{
    "id": 15,
    "cityId": 3538,
    "City": {
        "cityId": 3538,
        "countryId": 4
    }
}

为什么它返回cityId

当然可以排除以下字段:

static getByIdWithCity(id) {
    return this.findOne({
        where: {
            id: {
                [Op.eq]: id
            }
        },
        attributes: { exclude: ['cityId'] },
        include: [{
            model: City,
        }],
        raw: false
    });
}

但这是正确的方法吗?

1 个答案:

答案 0 :(得分:-1)

它返回-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8243,因为它是在模型中定义的。

是的,cityId可以很好地做到这一点,另一种实现相同结果的方法是使用exclude选项(基本上是attributes)显式地编写您想要的属性: / p>

include

所以与:

static getByIdWithCity(id) {
    return this.findOne({
        where: {
            id: {
                [Op.eq]: id
            }
        },
        attributes: ['id'],
        include: [{
            model: City,
        }],
        raw: false
    });
}

关于“正确方法”如何处理,我认为这取决于:

attributes: { include: ['id'] } 可以派上用场,例如,您想从查询中返回的不仅仅是一个属性,例如,假设一个exclude模型总共有13个属性,而您希望它们中的2个除外在这种情况下,仅使用User而不是使用exclude选项显式写入所有11个属性更有意义。

反之亦然:
如果只想返回13个属性中的2个,则使用attributes选项显式地编写所需的属性会很方便,在这种情况下,显式地编写它们比排除其余11个属性更有意义。

在这里,您只有一个属性attributes,并且只想排除一个属性id,无论您使用cityId还是{{1} },因为它们将运行相同的查询:include,并且您只需从模型定义中删除exclude(如果不需要),即可将其保留在迁移中。