【问题标题】:Sequilize.js - Association, 2 tablesSequelize.js - 关联,2 个表
【发布时间】:2017-03-12 22:53:09
【问题描述】:

使用的技术:Node.js、Express.js、Sequilize.js

我正在尝试连接两个表。有一个user 表和一个color 表。

color 属于useruser 可以有一种颜色。

我的文件结构:

My Project
|__config
   |__db.js
|__models
  |__user.js
  |__color.js
|__routes
  |__index.js
|__app.js

在我的user.js 文件中:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('user', {
        /* attributes, such as: username */
    });
};

在我的color.js 文件中:

module.exports = function(sequelize, DataTypes) {
    return sequelize.define('color', {
        color: {
            type: DataTypes.STRING,
            allowNull: false
        }
    });
};

然后在db.js 这是我配置这些文件的地方:

const db = {};

db.sequelize = sequelize;
db.Sequelize = Sequelize;

db.user = sequelize.import('../models/user.js');
db.color = sequelize.import('../models/color.js');


db.color.belongsTo(db.user);
db.user.hasOne(db.color);

module.exports = db;

现在是麻烦的开始。当某人创建新的user 帐户(使用POST 请求)时,他们还必须选择color。所以用户信息将进入user 表,颜色信息将进入color 表......但是我该怎么做呢?如何在创建阶段链接这两个表。以下是我目前所拥有的。

我的index.js文件中的POST请求是这样的:

const express = require('express');
const router = express.Router();
const db = require('../config/db');

router.post('/createNewUser', function(req, res) {
    const username = req.body.username
    const color = req.body.color

    db.user.create({
        username: username
        color: color
    }, {
       include: db.color
   }).then(function(result) {
        //do something
   }).catch(function(err) {
        //in case of error
   });
});

创建表格工作正常(所有配置代码都在app.js 文件中,此处不包含)。表被创建;用户名放在user 表中,颜色放在color 表中,但color 表中的userIDnull.

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    好的,问题解决了。在我创建新用户和颜色的地方,它应该如下所示:

    router.post('/createNewUser', function(req, res) {
        const username = req.body.username
        const color = req.body.color
    
        db.color.create({
            color: color
            user: {
                username: username
            }
        }, {
           include: [db.color]
       }).then(function(result) {
            //do something
       }).catch(function(err) {
            //in case of error
       });
    });
    

    这会将 2 个表格链接在一起;它将自动在color 表中创建一个名为userID 的列,该列与user 表中的id 的值相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多