Skip to content

Instantly share code, notes, and snippets.

@elleryq
Created March 25, 2015 07:01
Show Gist options
  • Save elleryq/ef818a8ffaf0dffacf7f to your computer and use it in GitHub Desktop.
Save elleryq/ef818a8ffaf0dffacf7f to your computer and use it in GitHub Desktop.
node-orm2 一對多的例子
// db 是用 orm.connect({protocol: "mysql", ....}, function(err, db) {}); 的 callback 所帶出的。
var Category = db.define('category', {
name: { type: 'text', required: true},
}, {}
});
var Food = db.define('food', {
name: { type: 'text', required: true},
price: { type: 'number', required: true},
}, {}
});
// one to many.
Food.hasOne("category", Category, {reverse: 'foods'});
// create
Category.create({ name: "general"}, function(err, category) {
if(err) { console.log(err); return; }
console.log(category); // 已經建立好的 category
Food.create({ name: "meet", category_id: category.id, price: 1000}, function(err, food) {
if(err) { console.log(err); return; }
console.log(food); // 已經建立好的 food
});
});
// query
Category.get(1, function(err, category) {
console.log(category);
console.log(category.getFoods());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment