sequelize.js - 如何自动创建一个 1 :1 relationship?

标签 sequelize.js

我有一个型号User有一个UserSettings与之相关的记录(一对一)。我想这样当我创建 User自动UserSettings 中创建记录具有默认值的表。

我尝试了一大堆不同的钩子(Hook)组合(beforeCreate、beforeValidate、afterCreate)。似乎没有任何效果。

它在我调用 User.create 并包含 UserSettings 关系时起作用,但我不想传入默认对象并添加“包含”。

想法?

最佳答案

我有一个 1:m + n:m 关联,但我认为这对您的案例来说不是问题。
目前我不知道是否有自动功能,但我用那个解决方法做到了。
在我的情况下是
键 1:m 郎
关键 n:m 产品
此刻我创建了一个 Key,我使用了 Result 并使用 Resulted ID new Langs 创建。
之后,使用关联产品创建 key 。

export function create(req, res) {
  return DictKey.create(req.body.body)// Create a Key
    .then((res)=> {
      for (var i = 0; i < req.body.langs.length; i++) {
        DictValue.create({//Create Associated Languages 
          lang_id: req.body.langs[i],
          key_id: res._id
        })
      }
      return res;
    })
    .then((key)=>{
      return key.addProduct(req.body.products);//Create Products
    })
    .then(respondWithResult(res, 201))
    .catch(handleError(res));
}

在您的模型定义中,您可以设置默认值,因此您不需要传递任何内容。
'use strict';

export default function(sequelize, DataTypes) {
  return sequelize.define('dict_Keys', {
    _id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    type: {
      type: DataTypes.INTEGER,
      allowNull:false,
      defaultValue: 0 // DefaultValue if nothing is passed
    },
  },{
    tableName: 'Keys'
  });
}

所以在你的情况下,它可能是这样的
export default function(sequelize, DataTypes) {
  return sequelize.define('UserSettings', {
    _id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    YourColumnName: {
      type: DataTypes.WhatYouWant,
      allowNull:CaseYouNeed,
      defaultValue: 0 // DefaultValue if nothing is passed
    }
}


   export function create(req, res) {
      return User.create(req.body)// Create a User
        .then((res)=> {
          UserSettings.create(
           //Create Associated Settings
           //send with Values or without which the DefaultValues will handle
)
          }
          return res;
        })
        .then(respondWithResult(res, 201))
        .catch(handleError(res));
    }

我希望这可以帮助你 。

关于sequelize.js - 如何自动创建一个 1 :1 relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40855442/

相关文章:

node.js - 如何使用自定义名称在 sequelize-cli 中定义自定义主键

mysql - 如何在 sequelize 中执行事务和回滚?

javascript - Node.Js 使用 sequelize/body 解析器和 mysql 添加记录

sequelize.js - 使用 Sequelize 关联模型的方法是否正确?

postgresql - 使用包含表中的 jsonb 数据类型对第一级查询的 where 子句进行后续处理

mysql - Node Sequelize with Mysql order by,最后需要空值

mysql - SequelizeJS - hasMany 到具有连接表的同一个表上的 hasMany

javascript - 我的 POST 有什么问题,导致 req.body 为空

node.js - sequelize 查询的可选参数

javascript - 通过 json 模式 Sequelize 定义模型