question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Include problem for multiple foreign keys of the same model

See original GitHub issue

Hi folks, I just found a problem in the case shown below. I don’t know yet, whether it’s a wrong behavior or whether I did something wrong. It’s basically about the List -> Task table join.

1.) It doesn’t matter what include options I take, there is no chance to join both foreign keys. Even something like “include: { all:true }” doesn’t work.

2.) The current result looks like:

[{
    "createdAt": "...",
    "updatedAt": "...",
    "dailyTask": 1,
    "weeklyTask": 2,
    "Task": {
        "id": 2,
        "description": "clean your room",
        "createdAt": "...",
        "updatedAt": "..."
    }
}]

But is there a chance to get it like, or wouldn’t be it actually better to have it like:

[{
    "createdAt": "...",
    "updatedAt": "...",
    "dailyTask": 1,
    "weeklyTask": {
        "id": 2,
        "description": "clean your room",
        "createdAt": "...",
        "updatedAt": "..."
    }
}]

And what I’m actually trying to have, should look like:

[{
    "createdAt": "...",
    "updatedAt": "...",
    "dailyTask": {
        "id": 1,
        "description": "brush your teeth",
        "createdAt": "...",
        "updatedAt": "..."
    },
    "weeklyTask": {
        "id": 2,
        "description": "clean your room",
        "createdAt": "...",
        "updatedAt": "..."
    }
}]

Any idea, whether it’s a bug, or how I could do it?

var co = require('co');
var Sequelize = require('sequelize');
var sequelize = new Sequelize('postgres://postgres:postgres@localhost:5432/test', {
    logging: false
});

// Models
var Task = sequelize.define('Task', {
    description: Sequelize.STRING
});

var List = sequelize.define('List');

// Assoziations
Task.hasMany(List, {
    foreignKey: 'dailyTask'
});

Task.hasMany(List, {
    foreignKey: 'weeklyTask'
});

List.belongsTo(Task, {
    foreignKey: 'dailyTask'
});

List.belongsTo(Task, {
    foreignKey: 'weeklyTask'
});

co(function*() {

    var connection = yield sequelize.sync({
        force: true
    });

    var dailyTask = yield Task.create({
        description: 'brush your teeth'
    });

    var weeklyTask = yield Task.create({
        description: 'clean your room'
    });

    var list = yield List.create({
        dailyTask: dailyTask.id,
        weeklyTask: weeklyTask.id
    });

    var result = yield List.findAll({
        include: [Task]
    });

}).catch(function(err) {
    console.log(err);
});

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Comments:13 (8 by maintainers)

github_iconTop GitHub Comments

57reactions
ppetzoldcommented, May 15, 2015

Hi @pmhpereira, here the solution related to the example above:

List.belongsTo(Task, {
    as: 'weeklyTask',
    foreignKey: 'weeklyTaskFk'
});

When you want to join the Task table, simply do the following on the include object:

{
    include: [{
            model: Task,
            as: 'weeklyTask'
     }]
}

Hope it helps!

43reactions
mickhansencommented, May 8, 2015

You’ll need to add an alias to one or both of those associations, currently they are overwriting eachother. Something like:

List.belongsTo(Task, {
    as: 'dailyTask',
    foreignKey: 'dailyTask'
});

List.belongsTo(Task, {
    as: 'weeklyTask',
    foreignKey: 'weeklyTask'
});

However it’s not possible to have an association be named the same as a foreign key, so you need to either rename your foreign keys or set your association aliases to something different.

Closing since a question (although still happy to help)

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Add Multiple Foreign Keys to Same Table and Not Get ...
Articles explains how to add multiple foreign keys to same table in SQL Server using the SQL queries to add foreign keys. Learn...
Read more >
Problem for multiple foreign keys of the same model
You've included an alias (test), but it does not match the alias(es) defined in your association (AggregateReview). My Model Below
Read more >
Multiple foreign keys for the same model in Rails 6 - Medium
Here, we have two models: User and Meeting. They have a 1..N relation, so one User will be part of a meeting and...
Read more >
How to Create a Table With Multiple Foreign Keys in SQL?
A table can have multiple foreign keys based on the requirement. ... The number and type of keys can be checked in the...
Read more >
3 common foreign key mistakes (and how to avoid them)
The easiest way to avoid this issue is to ensure that all columns linked to each other with foreign keys share the same...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found