Alias Sequelize



我在sequelize:中有这个查询

Domicilio.hasMany(User, {foreignKey: 'UserId'});
const abonados = await Domicilio.findAll({include: User});

结果如下:

选择domicilioDomicilioId_usersUserId作为_users.UserId_usersUserName作为_users.UserName_usersFullName作为_users.FullName_usersPassword作为_users.Password_usersDocumento作为_users.Documento_usersCuit作为_users.Cuit_usersEmail作为_users.Email_usersFechaBajada作为_users.FechaBajada_usersFechaContrato作为_users.FechaContrato_usersFechaNacimiento作为_users.FechaNacimiento_usersPhone作为_users.Phone_usersFailedPasswordCount作为_users.FailedPasswordCount_usersIsActive作为_users.IsActive_usersIsLocked作为_users.IsLocked_usersIsTestUser作为_users.IsTestUser_usersLastLoginDate作为_users.LastLoginDate_userscreatedAt作为_users.createdAt_userscreatedBy作为_users.createdBy_usersdeletedAt作为_users.deletedAt_usersdeletedBy作为_users.deletedBy_usersupdatedAt作为_users.updatedAt_usersupdatedBy作为_users.updatedBy_usersCondicionIVAId作为_users.CondicionIVAId_usersOnuId作为_users.OnuId_users。从domicilio作为domicilioServicioId作为_users.ServicioId左外连接_user作为_usersdomicilio上。DomicilioId_usersUserId

但是我不需要table_user的每一列的ALIAS。E.g _user.UserId我只需要每个列的名称,不需要别名。有什么办法解决这个问题吗?

有一些方法可以更改返回列的值

  • 首先,我建议您只获取真正需要的列通过您在模型端点的方式,响应是简洁的。

    请参阅下面的代码,您可以在其中查看如何提供关联中的别名,您在其中提供的别名就是包含期间使用的期望的行为。此外,您可以使用选项调整findAll参数,如{raw: true}

    官方文档:

    https://sequelize.org/master/manual/assocs.html

    https://sequelize.org/master/class/lib/model.js~Model.html#静态方法findAll

    Ship.belongsTo(Captain, { as: 'leader' }); // This creates the `leaderId` foreign key in Ship.
    // Eager Loading no longer works by passing the model to `include`:
    console.log((await Ship.findAll({ include: Captain })).toJSON()); // Throws an error
    // Instead, you have to pass the alias:
    console.log((await Ship.findAll({ include: 'leader' })).toJSON());
    // Or you can pass an object specifying the model and alias:
    console.log((await Ship.findAll({
    include: {
    model: Captain,
    as: 'leader'
    }
    })).toJSON());
    

  • 第二种但不是很推荐的方法是提供一个原始查询参数[不要使用javascript模板字符串来传递args]在这里你可以控制参数和条件

    用于原始查询的文档:https://sequelize.org/master/manual/raw-queries.html


  • 最后,您可以在属性中使用别名来自定义值的键到任何你喜欢的

    const abonados = await Domicilio.findAll({
    include: User,
    attributes: [['UserId', 'newUserId'], ['UserName 'newUserName']]
    });
    

p.S:文字有时也会派上用场。

最新更新