gpt4 book ai didi

javascript - 模型包含选项将属性作为具有定义别名的单个值而不是具有属性的对象返回

转载 作者:行者123 更新时间:2023-12-03 22:24:59 24 4
gpt4 key购买 nike

我有 2 个模型:

  • Property
  • Account
  • Property hasOne Account属性(property)
    Property.belongsTo(models.Account, {
    as: 'account',
    foreignKey: 'accountNumber'
    });
    帐户
    Account.hasOne(models.Property, {
    as: 'property',
    foreignKey: 'accountNumber'
    });
    findAll 查询中,我有
    const properties = await Property.findAll({
    attributes: ['accountNumber'],
    include: [
    {
    model: Models.Account,
    as: 'account',
    attributes: ['organisation', 'email'],
    },
    ]
    });
    这会为每个项目返回一个对象,例如;
    { 
    "accountNumber":"AC0012",
    "account":{
    "organisation":"Example Org",
    "email":"email@email.com"
    }
    }
    然而,我的目标是,
    { 
    "accountNumber":"AC0012",
    "accountOrganisation":"Example Org",
    "accountEmail":"email@email.com"
    }
    当前MySQL查询如下;
    SELECT `Property`.`id`, 
    `Property`.`account_number` AS `accountNumber`,
    `account`.`account_number` AS `account.accountNumber`,
    `account`.`organisation` AS `account`.`organisation`,
    `account`.`email` AS `account.email`
    FROM `property_dev`.`property`
    AS `Property`
    LEFT OUTER JOIN `property_dev`.`account` AS `account`
    ON `Property`.`account_number` = `account`.`account_number`
    我需要更新使用的别名;
    `account`.`organisation` AS `account`.`organisation`, 
    `account`.`email` AS `account.email`
    `account`.`organisation` AS `accountOrganisation`, 
    `account`.`email` AS `accountEmail`
    我怎样才能做到这一点?这似乎很简单,但我似乎无法查询正确的解决方案。我可能在搜索中使用了不正确的术语,浏览官方文档并没有找到解决方案。
    任何帮助将不胜感激

    最佳答案

    您可以使用带有 [value, key] 的数组为连接的列添加别名,其中 value 是包含模型的 sequelize.col() 值。由于您只需要原始 JSON 结果,您还可以传入 raw: true 以不将结果解析到模型实例以获得更好的性能。

    const properties = await Property.findAll({
    attributes: [
    'accountNumber',
    [sequelize.col('account.organisation'), 'accountOrganisation'],
    [sequelize.col('account.email'), 'accountEmail'],
    ],
    include: {
    model: Models.Account,
    as: 'account',
    attributes: [],
    },
    raw: true,
    });

    关于javascript - 模型包含选项将属性作为具有定义别名的单个值而不是具有属性的对象返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64903669/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com