Hobbyist
Hobbyist

Reputation: 16182

X is not associated to Y

I've been following the documentation of sequelize quite heavily and I've run into a problem when I got to relations. Here's my very simple code creating two extremely basic 1:1 relations using belongsTo

import Sequelize, { STRING, INTEGER, TEXT } from 'sequelize';

const sequelize = new Sequelize('dbname', '', '');

const User = sequelize.define('user', {
    name: STRING,
    age: INTEGER
});

const Item = sequelize.define('item', {
    name: STRING,
    price: INTEGER
});

Item.belongsTo(User);

sequelize.sync({ force: true }).then(() => {
    User.create({
        name: 'Hobbyist',
        age: 22,
        Item: {
            name: 'Phone',
            price: 199
        }
    }, {
        include: [ Item ]
    });
});

Error that I'm getting:

Unhandled rejection Error: item is not associated to user!

Upvotes: 4

Views: 3907

Answers (1)

Ivan Drinchev
Ivan Drinchev

Reputation: 19581

Sequelize works with reciprocal relationships.

So if you want to have Items belong to User you probably want to have User has one Item as well.

In your case you have associated User to Item, but not Item to User. So let's do it by adding :

Item.belongsTo(User);
User.hasOne(Item); // this line

Now Sequelize knows that every user has one Item, which can give us the opportunity to make JOIN queries.

The way that the library handles the properties of the associations is by the table name. So in your case you will also need to rename Item to item, like this :

User.create({
    name: 'Hobbyist',
    age: 22,
    item: {
 // ^ item, not Items
        name: 'Phone',
        price: 199
    }
}, {
    include: [ Item ]
});

Upvotes: 10

Related Questions