Question

I am new to ORMs and I am currently working on understanding the associations in Sequelize using Express. The issue I'm dealing with now is the hasOne and belongsTo methods and how they should be called and used in my particular situation.

There is a simple relationship between two tables

CREATE TABLE rocks(
    rock_id BIGINT 
        NOT NULL AUTO_INCREMENT,
    name varchar(255)
        NOT NULL, 
    rock_mode_id BIGINT
        NOT NULL,   
    PRIMARY KEY (rock_id),
    FOREIGN KEY (rock_mode_id) REFERENCES rock_modes(rock_mode_id),
);

CREATE TABLE rock_modes (
    rock_mode_id BIGINT 
        NOT NULL AUTO_INCREMENT,
    rock_mode varchar(255),
    PRIMARY KEY (rock_mode_id)
);

So in the javascript, I am attempting to do this after the models are defined and placed in a "db" object:

db.rock.hasOne(db.rock_mode, { foreignKey: 'rock_mode_id' });
db.rock_mode.belongsTo(db.rock, { foreignKey: 'rock_mode_id' });

Then, when I am trying to render all the data:

test: function(req, res) {
    db.rock
    .findAll({include: 
    [{ model: db.rock_mode, on: 'rock_mode_id' }]})
    .success(
        function(rocks) {
            var rockString = "";
            var foundRockMode = "";
            rockString += "<h2>Rocks</h2>";
            for(var i = 0; i < rocks.length;i++){
                rockString += JSON.stringify(rocks[i])+"<br />";

            }
            res.render('test', {
                  title: 'A Page Called Test',
                  body: rockString
            });
        })
  },

When I run the page I get the error:

Error: ER_BAD_FIELD_ERROR: Unknown column 'rock_mode.createdAt' in 'field list'

What I am ultimately attempting to do is to be able to access the "name" field of the rock_modes and print it out from a rock object.

Was it helpful?

Solution

createdAt and updatedAt are fields being added into your models and related tables by default. You can turn off this behavior by general settings when attaching sequelize into your project.

var sequelize = new Sequelize( 'dbname', 'dbuser', 'password', {
            host: 'hostname',
            define: {
                timestamps: false
            }
        });

Here are docs for this issue:

http://sequelizejs.com/docs/latest/models#definition http://sequelizejs.com/docs/latest/models#configuration

BTW: when you trying to fetch entity with related association (eager loading) you do not need to specify foreign key, since it is already specified in association definition.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top