Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize js 'include' and 'raw'

I have a relation between two entites like (every chest has one user)

entities.Chest.belongsTo(entities.User)

i want to retrieve all chests and their users in one query, so i do

entities.Chest.findAll({include:[{model: entities.User}]})

But i prefer to manipulate them as plain objects, i do

entities.Chest.findAll({raw:true, include:[{model: entities.User}]})

And the result does not include users at all, how can i achieve this?

like image 939
Andrew McFinley Avatar asked Nov 29 '16 20:11

Andrew McFinley


2 Answers

This syntax helps for me. You haven't to iterate your records. Just use nest: true and raw: true in pairs;

entities.Chest.findAll({
    raw:true,
    nest: true,
    include:[entities.User]
})
like image 191
Victor Fazer Avatar answered Oct 08 '22 00:10

Victor Fazer


as you see, raw has some problems with joins (there is an issue) try just use instance method #toJSON

entities.Chest.findAll({include:[{model: entities.User}]})
  .then(function(chestsSeq){
    var chests = chestsSeq.toJSON(); //same as chestsSeq.get({});
    //do something with raw chests object
  });
like image 37
Rudolf Manusachi Avatar answered Oct 07 '22 23:10

Rudolf Manusachi