0

In my project I am using MySQL database and Sequelize Js, I have two models created:

Post code model:

module.exports = function(sequelize, Sequelize) {

var Post_code = sequelize.define('post_code', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER(11)
    },

    code: {
        type: Sequelize.STRING(16),
        allowNull: false,
        unique: true
    },

    city: {
        type: Sequelize.STRING(45),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Post_code.associate = function(models) {
    models.post_code.hasMany(models.building);
};

   return Post_code;
}

Building model:

module.exports = function(sequelize, Sequelize) {

var Building = sequelize.define('building', {

    id: {
        autoIncrement: true,
        primaryKey: true,
        allowNull: false,
        type: Sequelize.INTEGER(11)
    },

    name: {
        type: Sequelize.STRING(100),
        allowNull: false
    },

    number: {
        type: Sequelize.INTEGER(11),
        allowNull: false
    },

    address: {
        type: Sequelize.STRING(255),
        allowNull: false
    },

    latitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    },

    longitude: {
        type: Sequelize.DECIMAL(9,6),
        allowNull: false
    }
},{
    freezeTableName: true,
    underscored: true
});

Building.associate = function (models) {
    models.building.belongsTo(models.post_code, {
        foreignKey: {
            allowNull: false
        }
    });

    models.building.hasMany(models.flat);
};

    return Building;
};

They are in relation one to many, it follows that Post code has many Buildings:

enter image description here

I want to add new building to database, when POST request is send to this route:

"/post-codes/:post_code_id/buildings"

I have access to post_code_id but I don't know how to correctly associate post_code model with building.

I was trying to do something like this:

models.post_code.findById(req.params.post_code_id)
.then(function(postCode){
    postCode.setBuilding(
        models.building.create({
        }).then(function(building){});  
    );    
});

But without result. I would be grateful if someone could explain how to make inserts correctly.

2
  • shouldn't you just need add the Building adding the Post-codeId to the object , from the parameter that you receive? Commented Mar 9, 2018 at 22:44
  • @Ellebkey Yes, that's correct, but I am searching for some build-in methods of making associations inside Sequelize. Other thing is that, yes, I can add post_code_id directly to building that I am going to create, but if something will happens that this parameter will be 'id' of post_code that does not exist in database, I will got an error. I didn't find simple explanation, but there is 'include' option inside model.create that I can use to create association probably in more secure way. Commented Mar 9, 2018 at 22:52

1 Answer 1

1

I haven't heard about the include option on create, but you can do something like this:

db.post_code.find({
  where: {
    id: req.params.post_code_id
  }
}).then(post_code => {
  if (!post_code) {
    return res.status(404).send({
      message: 'No post_code with that identifier has been found'
    });
  } else {
    //create here your building
  }
}).catch(err => {
  return res.jsonp(err)
});

I don't know if this is the best way to do it, but it verify first if the post_code exists.

Sign up to request clarification or add additional context in comments.

3 Comments

link doc Here is link to documentation about this option, maybe if you want you can take a look. Anyway thank you for your respond.
that's how define a N:M relationship, on your case you only need a 1:N relation. The include is use it when you need to do a join. So you'll include de post_code when you use find on Building cause it belongsTo
but if you will take a look for section 'Creating elements of a "HasMany" or "BelongsToMany' association", my case consider "BelongsToMany" because building belongs to many post_codes, and there they are presenting way to create/associate product with many tags, and next, they are setting tags:(key) as array of tags/objects

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.