代码之家  ›  专栏  ›  技术社区  ›  theJuls

在Sequelize模型中,如何将一列的默认值设置为与另一列相同?

  •  0
  • theJuls  · 技术社区  · 7 年前

    我有一个简单的模型,带有 _id 列,但有一个辅助id,我想将其默认为 _身份证 柱这就是模型当前的样子:

    const sequelize = app.get('sequelize')
    
    sequelize.define('myTable', {
      _id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true
      },
      otherId: {
        type: Sequelize.TEXT,
        allowNull: false
      }
      someField: {
        type: Sequelize.TEXT,
        allowNull: false
      }
    })
    

    所以如果我不为 otherId 当我插入新行时,我希望它的值与 _身份证 这能做到吗?如果是的话,我该如何实现这一点?

    1 回复  |  直到 7 年前
        1
  •  2
  •   bad_coder Singh    4 年前

    您只需从另一列通知Sequelize to default:

    otherId: {
        type: Sequelize.TEXT,
        allowNull: false,
        defaultValue: Sequelize.col('_id')
    }
    
        2
  •  0
  •   malik kurosaki    5 年前

    也许这不是你想要的,但希望它能为你提供参考

    模型

    class ModelPengguna extends Model{}
    ModelPengguna.init({
        user_id: {
            type: Sequelize.UUID,
            defaultValue: Sequelize.UUIDV1
        },
        name: {
            type: DataTypes.VIRTUAL,
            get(){
                return `/${this.id}/${this.user_id}`
            }
        }
    },{sequelize})
    

    控制者

    const lihat = await pengguna.findAll();
    console.log(JSON.stringify(lihat, null, 2))
    

    后果

    [
      {
        "name": "/1/ae0c6760-3c54-11eb-80ed-59fb8d2c0509",
        "id": 1,
        "user_id": "ae0c6760-3c54-11eb-80ed-59fb8d2c0509",
        "createdAt": "2020-12-12T08:33:15.991Z",
        "updatedAt": "2020-12-12T08:33:15.991Z"
      }
    ]
    
    推荐文章