-
Notifications
You must be signed in to change notification settings - Fork 376
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to insert a new record with relations? #162
Comments
It's not documented properly, but it's there. Whenever you do an association, accessors such as get, set, has, and del are added. var Person = db.define('person', {
name : String
});
var Animal = db.define('animal', {
name : String
});
Animal.hasOne("owner", Person); // assumes column 'owner_id' in 'animal' table
// get animal with id = 123
Animal.get(123, function (err, Foo) {
// Foo has getOwner(), setOwner(), hasOwner(), etc.
}); You can check the source here; usage in the test files here. |
I'm starting to think we need a wiki.. |
Did I misunderstand the original question? Is there a way to set the associations when calling Animal.create([{
name: 'kittycat',
owner: personInstance
}], ... Of course the example given by @rainulf gave works, but I think it'd be much cleaner this way. |
There's no option to create several instances of different models in one call, but you can create the instances manually and when you call var Person = db.define('person', {
name : String
});
var Animal = db.define('animal', {
name : String
});
Animal.hasOne("owner", Person);
// ...
var John = new Person({ name: "John" });
var Deco = new Animal({ name: "Deco" });
Deco.setOwner(John, function () {
// John should be saved (to fetch it's ID) and also Deco should be saved
}); |
I'm going to try this in a couple of minutes. If I'm successful I'll post an example. |
…nstances (#162) There are more stuff to do but at least creating new instances should be more easy for users.
You should now be able to do something like: var John = new Person({
name: "John",
surname: "Doe",
pets: [ new Pet({ name: "Deco" }), ... ]
});
John.save(function (err) {
// assuming Person.hasMany("pets", Pet), Deco should be saved, so as John
}); |
Awesome! |
I'm going to close this for now. I'll add some tests a few tiny tweaks in the meantime. |
I have ModelA that hasMany ModelB elements, how do I insert a new modelA with the associations already there for modelB? Or how do I associate the new record with the records of ModelB after the first one is saved?
Thanks!
The text was updated successfully, but these errors were encountered: