Darlyn
Darlyn

Reputation: 4940

Relations in sqlize / hasOne does not work

I am trying to create 1:1 relation between table of shops and product. Each product should have an foreign key of shop table and each shop should have foreign key of product.

i have defined those two tables.

module.exports = function( sequelize , DataTypes ){
    var shops = sequelize.define('shops',{
            id: {
                type: DataTypes.INTEGER,
                allowNull:false,
                primaryKey:true,
                autoIncrement:true
            },
            name:{
                type:DataTypes.STRING,
                allowNull:false
            },
            address:{
                type: DataTypes.STRING,
                allowNull:false
            },
            web:{
                type: DataTypes.STRING,
                allowNull:false
            },
            price:{
                type: DataTypes.INTEGER,
                allowNull:false
            }
    })
    return shops
}

`

var shop = require('./shops.js');

module.exports = function( sequelize , DataTypes ){
    var component = sequelize.define('component',{
            id: {
                type: DataTypes.INTEGER,
                allowNull:false,
                primaryKey:true,
                autoIncrement:true
            },
            name:{
                type: DataTypes.STRING,
                allowNull:false
            },
            storage:{
                type: DataTypes.INTEGER,
                allowNull:false
            },
            bilance:{
                type: DataTypes.INTEGER,
                allowNull:false
            }
    },{
        classMethods:{
         associate:function(models){
          component.hasOne(shop,{foreignKey:'foreign_key'})
         }
        }
    })
    return component;
}

inside db.js file a connected it using.

db.shop.belongsTo(db.component)
db.component.hasOne( db.shop ,{foreignKey : 'shop_id'})

but this added componentId {foreign key} and shop_id another foreign key ,both of them to the shop table.

If i replace 1:1 relation if 1:n e.g

db.component.hasMany(..)

It does the same thing , adds both foreign keys into the shops table

Upvotes: 0

Views: 727

Answers (1)

James111
James111

Reputation: 15903

You need to reference shop from the models object provided to you in the callback method. So in this case you'd do:

classMethods:{
    associate:function(models){
        component.hasOne(models.shop,{foreignKey:'component_shop_FK'})
    }
}

Note if you want to add a constraint (such as not null) to the FK, simple add allowNull: false.

I believe you're referencing the wrong model. You've listed 'shops' for your shop object, so try changing models.shop to models.shops!

Upvotes: 1

Related Questions