New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Sequelize create object with association not working #5138
Comments
Looks like |
Howdy mate, As requested ran console.log(Object.keys(location.rawAttributes)); and got
So weatherId in table is WeatherId in Model. First attempt - Take 2weatherId: weatherId and it works. Thanks for the help Thanks again |
The default foreign key name is based on the model name, but you can overwrite it with |
@mickhansen heeding you tip I have refactored all my 5 entities, dropped db, recreated and re-ran fixtures, then when she fires up I get
assuming its my Fish table as per SQL
mySql says this
My model says this 'use strict';
module.exports = function(sequelize, DataTypes) {
var Fish = sequelize.define('Fish', {
id: DataTypes.INTEGER,
length: DataTypes.INTEGER,
weight: DataTypes.INTEGER,
timeCaught: DataTypes.INTEGER,
notes: DataTypes.TEXT
}, {
classMethods: {
associate: function(models) {
// associations can be defined here
Fish.belongsTo(models.Rig, {foreignKey: 'rigId'});
Fish.belongsTo(models.Species, {foreignKey: 'speciesId'});
}
},
freezeTableName: true,
tableName: 'Fish',
timestamps: true
});
return Fish;
}; |
You'll need to add the foreign key option to both sides of the association (if you've defiend Rig hasMany Fish that needs the option aswell) |
Fantastic @mickhansen you saved me from drowning in the deep end. 👍 Now have time to finish the fish logging app before the trip starts in 3 weeks. |
See this StackOverflow for original reference, but I think this is a better place to get a response at the moment
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 as per follows and I am using migrations if this has anything to do with it: -
Location
MySQL describe for Location
Weather model
MySQL describe for Weather
Attempts
First attempt which fails with NULL weatherId
Second attempt which fails with NULL weatherId
Yet when I do an update this works: -
There are no errors in the logs, but still weatherId is NULL.
The SQL in the log does not include the weatherId as per: -
Can anyone help me with this, have spent so much time on this..
Peter
The text was updated successfully, but these errors were encountered: