简体   繁体   English

对关联不起作用的创建对象进行续集

[英]Sequelize create object with association not working

I am trying to create a record (Location) with an association (Weather) (insert with foreign key) and every which way I try I end up with a NULL value in the foreign key field weatherId . 我试图用关联(天气)(用外键插入)创建一个记录(位置),并且我尝试通过每种方式在外键字段weatherId中最终得到一个NULL值。

I have seen examples in the help with creating both the primary and secondary entities at the same time, but in this case I have preloaded the Weather table and the user is limited to selecting an item from a select list. 我在帮助中看到了同时创建主要实体和辅助实体的示例,但是在这种情况下,我已经预加载了Weather表,并且用户仅限于从选择列表中选择一项。

I have found similar issues but none have answered the problem. 我发现了类似的问题,但是没有一个问题得到了解答。

Sequelize [Node: 4.2.2, CLI: 2.2.1, ORM: 2.0.0-rc1, mysql: ^2.10.0] Sequelize [节点:4.2.2,CLI:2.2.1,ORM:2.0.0-rc1,MySQL:^ 2.10.0]

My models are: - 我的模型是:-

Location 位置

'use strict';
module.exports = function(sequelize, DataTypes) {
    var Location = sequelize.define('Location', {
        id: DataTypes.INTEGER,
        locationName: DataTypes.STRING
    }, {
        classMethods: {
            associate: function(models) {
                Location.hasMany(models.Rig);
                Location.belongsTo(models.Weather);
            }
        },
        freezeTableName: true,
        tableName: 'Location',
        timestamps: true
    });
    return Location;
};

MySQL describe for Location MySQL描述位置

mysql> desc Location;
+--------------+--------------+------+-----+---------+----------------+
| Field        | Type         | Null | Key | Default | Extra          |
+--------------+--------------+------+-----+---------+----------------+
| id           | int(11)      | NO   | PRI | NULL    | auto_increment |
| locationName | varchar(255) | YES  |     | NULL    |                |
| weatherId    | int(11)      | YES  |     | NULL    |                |
| createdAt    | datetime     | NO   |     | NULL    |                |
| updatedAt    | datetime     | NO   |     | NULL    |                |
+--------------+--------------+------+-----+---------+----------------+

Weather model 天气模型

'use strict';
module.exports = function(sequelize, DataTypes) {
    var Weather = sequelize.define('Weather', {
        id: DataTypes.INTEGER,
        weatherDescription: DataTypes.STRING
    }, {
        classMethods: {
            associate: function(models) {
                Weather.hasMany(models.Location);
            }
        },
        freezeTableName: true,
        tableName: 'Weather',
        timestamps: true
    });
    return Weather;
};    

MySQL describe for Weather MySQL描述天气

mysql> desc Weather;
+--------------------+--------------+------+-----+---------+----------------+
| Field              | Type         | Null | Key | Default | Extra          |
+--------------------+--------------+------+-----+---------+----------------+
| id                 | int(11)      | NO   | PRI | NULL    | auto_increment |
| weatherDescription | varchar(255) | YES  |     | NULL    |                |
| createdAt          | datetime     | NO   |     | NULL    |                |
| updatedAt          | datetime     | NO   |     | NULL    |                |
+--------------------+--------------+------+-----+---------+----------------+

First attempt which fails with NULL weatherId 首次尝试失败,并以NULL weatherId失败

models.Location.create({
    locationName: locationName,
    weatherId: weatherId

}).then(function(location) {
    res.redirect('/location');

}).catch(function(reason) {
    console.log(reason);
});

Second attempt which fails with NULL weatherId 第二次尝试以NULL weatherId失败

models.Location.create({
    locationName: locationName

}).then(function(location) {
    models.Weather.find({where: { id: weatherId } }).then(function(weather) {
        location.setWeather([weather]).then(function(location) {

            res.redirect('/location');

        }).catch(function(reason) {
            console.log(reason);
        });

    }).catch(function(reason) {
        console.log(reason);
    });

}).catch(function(reason) {
    console.log(reason);
});

Yet when I do an update this works: - 但是,当我进行更新时,它会起作用:-

models.Location.find({
    where: {
        id: locationId
    }
}).then(function(location) {
    if (location) {
        location.setWeather([weatherId]).then(function(location) {
            location.updateAttributes({
                locationName: locationName
            }).success(function() {
                res.redirect('/location');
            });
        });
    }
}).catch(function(reason) {
    console.log(reason);
    res.send(reason);
})

There are no errors in the logs, but still weatherId is NULL . 日志中没有错误,但weatherId仍为NULL

The SQL in the log does not include the weatherId as per: - 日志中的SQL不包含以下项的weatherId :-

INSERT INTO `Location` (`id`,`locationName`,`createdAt`,`updatedAt`) VALUES (NULL,'test me','2016-01-04 02:33:04','2016-01-04 02:33:04');

Can anyone help me with this, have spent so much time on this.. 任何人都可以帮我这个忙,在这个上花了很多时间。

Peter 彼得

This has been resolved at https://github.com/sequelize/sequelize/issues/5138 这已在https://github.com/sequelize/sequelize/issues/5138中解决

As requested ran console.log(Object.keys(location.rawAttributes)); 根据要求运行console.log(Object.keys(location.rawAttributes));

and got [ 'id', 'locationName', 'createdAt', 'updatedAt', 'WeatherId' ] 并得到了['id','locationName','createdAt','updatedAt','WeatherId']

So weatherId in table is WeatherId in Model. 因此,表中的weatherIdModel中的WeatherId

First attempt - Take 2 第一次尝试-参加2

weatherId: weatherId to WeatherId: weatherId weatherId:weatherId到WeatherId:weatherId

and it works. 而且有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM