问题描述
我正在将 Sequelize 与 Mysql 一起使用.
I'm using Sequelize with Mysql.
我有一张桌子:
物品
包含以下字段:
{Id,Name,Price}
我想在项目中与他自己建立一个自我关系.能够执行 Item.subItems 并获取属于该项目的所有子项目的列表的目标.
I want to made a self relation within the Item to himself.The target to be able to do Item.subItems and to get a list of all the sub items that belong to this item.
请告诉我如何在
包括:[{model:SubItem}]... 当我获取查询时.
我尝试了很多关系选项:
I have tried many option of relations:
Item.hasMany(Item,{ through: SubItem,as:'subItems'});
Item.hasMany(Item);
感谢您的帮助!
推荐答案
创建自引用
Item.hasMany(Item, {as: 'Subitems'})
使用包含查找子项
Item.find({where:{name: "Coffee"},include:[{model: Item, as: 'Subitems'}]})
请参阅下面的示例代码,
See the Sample code below,
var Sequelize = require('sequelize')
, sequelize = new Sequelize("test", "root", "root", {logging: false})
, Item = sequelize.define('Item', { name: Sequelize.STRING })
Item.hasMany(Item, {as: 'Subitems'})
var chainer = new Sequelize.Utils.QueryChainer
, item = Item.build({ name: 'Coffee' })
, subitem1 = Item.build({ name: 'Flat White' })
, subitem2 = Item.build({ name: 'Latte' })
sequelize.sync({force:true}).on('success', function() {
chainer
.add(item.save())
.add(subitem1.save())
.add(subitem2.save())
chainer.run().on('success', function() {
item.setSubitems([subitem1, subitem2]).on('success', function() {
/* One way
item.getSubitems().on('success', function(subitems) {
console.log("subitems: " + subitems.map(function(subitem) {
return subitem.name
}))
})
*/
//The include way you asked
Item.find({where:{name: "Coffee"},include:[{model: Item, as: 'Subitems'}]}).success(function(item) {
console.log("item:" + JSON.stringify(item));
})
})
}).on('failure', function(err) {
console.log(err)
})
})
日志数据如下:
item:{"id":1,"name":"Coffee","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":null,"subitems":[{"id":2,"name":"Flat White","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":1},{"id":3,"name":"Latte","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":1}]}
item:{"id":1,"name":"Coffee","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":null,"subitems":[{"id":2,"name":"Flat White","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":1},{"id":3,"name":"Latte","createdAt":"2014-08-05T06:25:47.000Z","updatedAt":"2014-08-05T06:25:47.000Z","ItemId":1}]}
这篇关于Sequelize - 自我引用有很多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!