无法与Sequelize建立一对一的关系

时间:2014-06-05 17:25:10

标签: javascript mysql node.js sequelize.js

我宣布:

Item.hasOne(Item, { foreignKey: 'parentAid', as: 'Parent' })

我问过:

Item.find({where : {aid: aid}, include: [Item]}).complete(function(err, article) { .. };

我得到了:

Error: Item is not associated to Item!

我做错了什么?

............................................... ...............................................

更新1

感谢Jan Aargaard Meier提供了有用的答案,我能够将事情改为:

ItemModel.belongsTo(ItemModel, { foreignKey: 'parentAid', as: 'Parent', foreignKeyConstraint: true });
ItemModel.hasMany(ItemModel, { as: 'Children', constraints: false });

this.articleRelations.push({
    model: ItemModel,
    as: 'Parent'
});

this.articleRelations.push({
    model: ItemModel,
    as: 'Children'
});

// ...

我的查询现在是:

{where : {aid: aid}, include: this.articleRelations}

但是我收到以下错误:

{
code : "ER_BAD_FIELD_ERROR",
errno : 1054,
sqlState : "42S22",
index : 0,
sql : "SELECT `item`.*, `Parent`.`aid` AS `Parent.aid`, `Parent`.`gid` AS `Parent.gid`, `Parent`.`title` AS `Parent.title`, `Parent`.`type` AS `Parent.type`, `Parent`.`parentAid` AS `Parent.parentAid`, `Parent`.`createdAt` AS `Parent.createdAt`, `Parent`.`updatedAt` AS `Parent.updatedAt`, `Parent`.`itemId` AS `Parent.itemId`, `Parent`.`aid` AS `Parent.aid`, `Parent`.`aid` AS `Parent.aid`, `Parent`.`aid` AS `Parent.aid`, `Children`.`aid` AS `Children.aid`, `Children`.`gid` AS `Children.gid`, `Children`.`title` AS `Children.title`, `Children`.`type` AS `Children.type`, `Children`.`parentAid` AS `Children.parentAid`, `Children`.`createdAt` AS `Children.createdAt`, `Children`.`updatedAt` AS `Children.updatedAt`, `Children`.`itemId` AS `Children.itemId`, `Children`.`aid` AS `Children.aid`, `Children`.`aid` AS `Children.aid`, `Children`.`aid` AS `Children.aid` FROM (SELECT `item`.* FROM `item` WHERE `item`.`aid`=2 LIMIT 1) AS `item` LEFT OUTER JOIN `item` AS `Parent` ON `Parent`.`aid` = `item`.`parentAid` LEFT OUTER JOIN `item` AS `Children` ON `item`.`aid` = `Children`.`itemId`;"

}

注意:  *表名为item  *查询包含itemId,我没有在任何地方定义。那似乎是一个错误?

供参考,这是我的模型:

ItemModel = sequelize.define('ExerciseItem', {
        aid: {type: Sequelize.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true},
        gid: {type: Sequelize.INTEGER.UNSIGNED},
        title: Sequelize.STRING(100),
        type: Sequelize.INTEGER.UNSIGNED,
        parentAid: Sequelize.INTEGER.UNSIGNED
    },{
        freezeTableName: true,
        tableName: 'item'
});

1 个答案:

答案 0 :(得分:1)

Item.find({where : {aid: aid}, include: [{ model: Item, as: 'Parent' }])

如果您为关系提供别名,则必须在执行预先加载时提供该别名(就像您在项目实例上调用getParent而不是getItem一样)

这是因为别名(使用as)允许您为同一模型创建多个关联,因此当您只提供模型时,无法知道您真正想要加载哪个模型。 / p>

我们一直在讨论使用关系调用的返回值的能力,例如:

var itemParentRelation = Item.hasOne(Item, { foreignKey: 'parentAid', as: 'Parent' })
Item.find({where : {aid: aid}, include: [itemParentRelation])
// or
Item.find({where : {aid: aid}, include: [item.relations.parent])

但是现在你必须使用帖子开头提供的代码:)