I'm using Sequelize with Mysql.
I have a table:
Items
that contain the fields:
{Id,Name,Price}
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.
and please show me how to include the new model in
include:[{model:SubItem}]... when i fetch the a query.
I have tried many option of relations:
Item.hasMany(Item,{ through: SubItem,as:'subItems'});
Item.hasMany(Item);
Thanks for the help!
To create the self reference
Item.hasMany(Item, {as: 'Subitems'}) 
To find subitems using include
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)
  })
})
And the log data is below:
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}]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With