简体   繁体   中英

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 .

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.

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]

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> 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> 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

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

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 .

The SQL in the log does not include the weatherId as per: -

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

As requested ran console.log(Object.keys(location.rawAttributes));

and got [ 'id', 'locationName', 'createdAt', 'updatedAt', 'WeatherId' ]

So weatherId in table is WeatherId in Model.

First attempt - Take 2

weatherId: weatherId to WeatherId: weatherId

and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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