[英]Unable to establish one-to-one relation with Sequelize
我宣布:
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'
});
Item.find({where : {aid: aid}, include: [{ model: Item, as: 'Parent' }])
如果為關系提供別名,則在進行急切加載時必須提供該別名(就像在項目實例上調用getParent
而不是getItem
)
這是因為別名(使用as
)使您可以創建與同一模型的多個關聯,因此,當您僅提供模型時,就沒有辦法讓續集知道您實際要加載的模型。
我們一直在談論使用關系調用的返回值的能力,例如:
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])
但是現在您必須使用帖子開頭提供的代碼:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.