Sequencing associations with foreign keys

I really miss this one at Sequelize. The .hasMany definition only works with mapping on an identifier. Let's take a typical project / task example. Let him then say that the project has a VERSION attribute and should be associated with tasks that have the same VERSION attribute.

I need a way to make the relationship be based on two attributes: ID and VERSION.

I strongly believe that we need a way to create associations based on several foreign keys (called composite keys)

In my project, I had to add a bunch of methods for models to provide getTasks replaced with a few keys.

If anyone has a suggestion, he welcomes.

+4
source share
1 answer

This is also what we need in our project. We added the functionality we need and use it daily in our project, but the functionality has not been fully tested, so we have not yet sent a transfer request.

However, you can find the code https://github.com/innofluence/sequelize/tree/newedge

specs/associations/composite-key.spec.js shows the API:

 Article = sequelize.define('Article', { 'title': Sequelize.STRING }, { instanceMethods: { item_key: 'article' } }); Label = sequelize.define('Label', { 'text': Sequelize.STRING }) Label.hasMany(Article, {foreignKey: "label_id", joinTableName: "item_label" }); Article.hasMany(Label, {foreignKey:{ "item_id": "id", "item": "item_key" }, joinTableName: "item_label" }); 

In this example, an article may contain several labels. The connection table ( item_label ) has the following rows: id, item, item_id, label_id . The important thing here is the last line, which shows that the link between Label and Article is a composite key. A foreign key is defined as a map, in which the keys are rows in the connection table, and the values ​​are the values ​​from the article row. You can see here that the item in item_label maps to item_key, which is the instance method for the article. This is because all articles have a key article, so there is no need to save it in db.

I hope this was helpful, and if you still have doubts, please feel free to post your continuation model code and I will try to help :-)

+5
source

All Articles