X 与 Y 无关 [英] X is not associated to Y

查看:62
本文介绍了X 与 Y 无关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在密切关注 sequelize 的文档,但在处理关系时遇到了问题.这是我使用 belongsTo

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

我遇到的错误:

Unhandled rejection Error: item is not associated to user!

推荐答案

Sequelize 处理互惠关系.

Sequelize works with reciprocal relationships.

因此,如果您希望 Items 属于 User,您可能希望 User 也有一个 Item.

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

现在 Sequelize 知道每个用户都有一个 Item,这可以让我们有机会进行 JOIN 查询.

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

库处理关联属性的方式是通过表名.因此,在您的情况下,您还需要将 Item 重命名为 item,如下所示:

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

这篇关于X 与 Y 无关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆