Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
585 views
in Technique[技术] by (71.8m points)

sequelize.js - 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!
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ]
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...