how do I keep the parent table available
-
22-06-2021 - |
Question
I have two models: User
and Phone
The User
model has a field called Phone_id
which is populated with the Phone.id
field.
I am trying to loop through all phones and display the phone name and associated user extension number.
However, because of callbacks (I think) the phone object has gone when I get to the success method of the getUser
method.
code is below :
var User = sequelize.import(__dirname + '/../models/User.js');
var Phone = sequelize.import(__dirname + '/../models/Phone.js');
Phone.hasOne(User,{ foreignKey: 'Phone_id'});
Phone.findAll().success(function(phones){
for (var i = 0; i < phones.length; i++) {
phones[i].getUser().success(function(user){
console.log(xxxx.Name, user.Extension);
});
});
How can I display the phone name and user extension in the console.log statement iow, what do I need to put in place of xxxx ?
thanks !
Solution
not tested but something like
var User = sequelize.import(__dirname + '/../models/User.js');
var Phone = sequelize.import(__dirname + '/../models/Phone.js');
Phone.hasOne(User,{ foreignKey: 'Phone_id'});
Phone.findAll().success(function(phones){
phones.forEach(function(phone) {
phone.getUser().success(function(phone) {
return function(user){
console.log(phone.Name, user.Extension);
}
}(phone))
})
});
OTHER TIPS
what you want to do is this:
var User = sequelize.import(__dirname + '/../models/User.js');
var Phone = sequelize.import(__dirname + '/../models/Phone.js');
Phone.hasOne(User,{ foreignKey: 'Phone_id'});
Phone.findAll().success(function(phones){
phones.forEach(function(phone) {
phone.getUser().success(function(user){
console.log(phone.Name, user.Extension);
});
})
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow