Inserting data with relations (Model.create()'s include field)

69 views
Skip to first unread message

Sveinn Fannar Kristjánsson

unread,
Nov 17, 2014, 7:08:25 AM11/17/14
to sequ...@googlegroups.com
Hello,

I'm trying to insert data into a table that has a one-to-many relation with another table, preferably in one SQL query.
For a more concrete example, let's say we have a Channels that has many Videos. So when inserting a new video I want to associate it with a specific channel without knowing the channel id (which is the foreign key).

I could do it like this, which is perfectly fine except it involves two SQL queries:

Channel.findOne({ name: 'My Channel' }) 

.then(function (channel) {

  channel.addVideo(Video.build({ name: 'My Video' }));

}); 


Do you know of another way to achieve this?
I noticed that Model.create() has an include option, is that intended for these kind of scenarios? If so, do you have an example of how it would be used?

Thanks.

Chad Robinson

unread,
Jan 4, 2015, 12:45:18 PM1/4/15
to sequ...@googlegroups.com
Just curious, how would you do this without SequelizeJS? The only good way that I can think of would be to do a sub-query during the INSERT to get the channel. We never wanted this with our application because we needed to do validation on the channel before trying to add videos to it - so we needed your load pattern below anyway. MySQL is almost faster than Redis for single-record ID-based loads, so this wasn't an issue for us. I'm curious to know if/how you solved your problem, though.

Richard Gustin

unread,
Mar 3, 2015, 11:27:17 AM3/3/15
to sequ...@googlegroups.com
Hey Sveinn,

CleverStack provides this feature through the ORM Module (clever-orm) , which uses SequelizeJS behind the scenes - By using the CleverStack Model Class you're able to define a single model, that can be used with ORM/Sequelize, but more importantly with other modules like our ODM Module (clever-odm), which uses MongooseJS to store data in MongoDB.

CleverStack allows you to create, update, remove/delete any associated model on any level of any association - for instance you could post a user, with an array of email addresses (where UserModel hasMany EmailModel)
This feature is implemented in roughly a dozen files in cleverstack's node-seed, clever-orm and clever-odm modules - in particular https://github.com/CleverStack/clever-orm/tree/master/lib/model/associations/nestedOperations.

To look at the code relating to the example i gave, (UserModel hasMany EmailModel) take a look at https://github.com/CleverStack/clever-orm/blob/master/lib/model/associations/nestedOperations/hasMany/afterCreate.js

To take a look at how you define models in CleverStack, see Model Definition from the Model Documentation

Cheers,
Richard
Reply all
Reply to author
Forward
0 new messages