You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sequelize如何创建带关联的action数据并返回关联结果

Sequelize创建记录后返回带关联数据的实现方法

Action.create()方法默认只会返回当前模型自身的字段,不会自动加载关联关系数据,要返回带关联的内容,按以下步骤操作即可:

前置检查

首先确认你已经在模型定义阶段配置好了Action和ActionType的关联关系,示例配置:

// Action模型中配置
Action.belongsTo(ActionType, {
  foreignKey: 'type_id', // 你当前使用的外键字段
  // 如果需要自定义关联返回的字段名,可以加as参数,后续查询要对应上
  // as: 'actionType'
})

推荐实现方案

创建完Action记录后,通过主键查询刚生成的记录,传入include参数指定要加载的关联模型即可,修改后的完整代码:

async create(req, res){
    const {minRoll,maxRoll,typeName} = req.body;

    const actionType = await ActionType.findOne({
        where: {name: typeName}
    });

    if(!actionType){
        return res.json({result:false});
    }

    const {id} = actionType;
    
    const action = await Action.create({
         minRoll: minRoll,
         maxRoll: maxRoll,
         type_id: id
    });

    // 带关联查询刚创建的记录
    const resData = await Action.findByPk(action.id, {
        include: [
            {
                model: ActionType
                // 如果关联配置时加了as参数,这里必须同步配置
                // as: 'actionType'
            }
        ]
    })

    return res.json(resData);
},

返回效果

配置完成后Postman中就能拿到带关联的返回结构,示例:

{
    "id": 61,
    "minRoll": 1,
    "maxRoll": 3,
    "type_id": 20,
    "ActionType": {
        "id": 20,
        "name": "传入的typeName对应值"
        // 其余ActionType模型的字段
    }
}

可选简化方案

如果不想创建后再查一次,也可以在拿到关联实例后直接通过关联方法创建记录,再手动拼接关联数据返回:

async create(req, res){
    const {minRoll,maxRoll,typeName} = req.body;

    const actionType = await ActionType.findOne({
        where: {name: typeName}
    });

    if(!actionType){
        return res.json({result:false});
    }

    // 直接通过关联方法创建action,不需要手动传type_id
    const action = await actionType.createAction({
        minRoll: minRoll,
        maxRoll: maxRoll
    })

    // 手动把关联数据挂到返回结果上
    action.dataValues.ActionType = actionType;
    return res.json(action);
},

注意:这个方案虽然少了一次数据库查询,但需要确保关联方法名和你配置的关联关系匹配,且手动挂载的关联数据不会经过模型的属性过滤,如果有字段脱敏需求建议用第一种查询方案。

内容的提问来源于stack exchange,提问作者Joseph Oliveira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:18:21