Created
January 12, 2015 20:10
-
-
Save andrest/0e463c35023d24ad103c to your computer and use it in GitHub Desktop.
Double JOIN on the same table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.get('/plans/:plan_id', function (req, res) { | |
models.Plan.find({ | |
where: {id: req.param('plan_id')}, | |
include: [ | |
{ | |
model: models.Order, | |
as: "pending_orders" | |
}, | |
{ | |
model: models.Order, | |
as: "completed_orders" | |
} | |
] | |
}) | |
.success(function(plan) { | |
res.json(plan); | |
}).error(function(err) { | |
res.status(400).json({error: err.message}); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
module.exports = function(sequelize, DataTypes) { | |
var Order = sequelize.define("Order", { | |
number: DataTypes.STRING, | |
total: DataTypes.DECIMAL(10,2), | |
state: DataTypes.STRING | |
}, { | |
classMethods: { | |
associate: function(models) { | |
Order.belongsTo(models.User, {foreignKey: 'user_id'}); | |
Order.belongsTo(models.Plan, {foreignKey: 'plan_id'}); | |
} | |
} | |
}); | |
return Order; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
module.exports = function(sequelize, DataTypes) { | |
var Plan = sequelize.define("Plan", { | |
shipment_interval: DataTypes.INTEGER, | |
payment_interval: DataTypes.INTEGER, | |
}, { | |
classMethods: { | |
associate: function(models) { | |
Plan.hasMany(models.Order, {foreignKey: 'plan_id', as: "completed_orders", scope: {state: "completed"}}); | |
Plan.hasMany(models.Order, {foreignKey: 'plan_id', as: 'pending_orders', scope: {state: "pending"}}); | |
} | |
} | |
}); | |
return Plan; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment