2015-08-13 2 views
1

Я создаю приложение для опроса, используя Node.js/Express и MySQL с Sequelize.js ORM.Sequelize.js Внешняя ссылка отношения «один ко многим»

У меня возникли проблемы с правильной установкой соотношения между двумя моделями. Я хотел бы иметь внешний ключ QId вопросов в таблице ответов.

// define the Questions table 
var Questions = sequelize.define('Questions', { 
    qId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true}, 
    question: Sequelize.STRING 
}, { 
    timestamps: false 
}); 

// define the Answers table 
var Answers = sequelize.define('Answers', { 
    aId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true}, 
    answer: Sequelize.STRING, 
    answer_count: { type: Sequelize.INTEGER, defaultValue: 0} 
}, { 
    timestamps: false 
}); 

// define one-to-many relationship 
Questions.hasMany(Answers, {as: 'Answers', foreignKey: 'qId'}); 

Questions.sync({force: true}).then(function() { 
    // OPTIONAL: create a new question upon instantiating the db using sequelize 
    Questions.create({question: 'what is your language?'}); 
    Questions.create({question: 'what is your drink?'}); 
    console.log('created Questions table'); 
    }).catch(function(error) { 
    console.log('error creating Questions table'); 
    }); 

Answers.sync({force: true}).then(function() { 
    Answers.create({answer: 'python', qId: 1}); 
    Answers.create({answer: 'javascript', qId: 1}); 
    Answers.create({answer: 'ruby', qId: 1}); 
    Answers.create({answer: 'c++', qId: 1}); 
    Answers.create({answer: 'manhattan', qId: 2}); 
    Answers.create({answer: 'cosmopolitan', qId: 2}); 
    console.log('created Answers table'); 
}).catch(function(error) { 
    console.log('error creating Answers table'); 
}); 

Но когда я делаю MySQL запросов:

select * from Questions, Answers where Answers.qId=2; 

он показывает следующее:

mysql> select * from Answers; 
+-----+--------------+--------------+------+ 
| aId | answer  | answer_count | qId | 
+-----+--------------+--------------+------+ 
| 1 | python  |   0 | 1 | 
| 2 | javascript |   0 | 1 | 
| 3 | ruby   |   0 | 1 | 
| 4 | c++   |   0 | 1 | 
| 5 | manhattan |   0 | 2 | 
| 6 | cosmopolitan |   0 | 2 | 
+-----+--------------+--------------+------+ 
6 rows in set (0.00 sec) 

mysql> select * from Questions; 
+-----+------------------------+ 
| qId | question    | 
+-----+------------------------+ 
| 1 | what is your language? | 
| 2 | what is your drink? | 
+-----+------------------------+ 
2 rows in set (0.00 sec) 

mysql> select * from Questions, Answers where Answers.qId=2; 
+-----+------------------------+-----+--------------+--------------+------+ 
| qId | question    | aId | answer  | answer_count | qId | 
+-----+------------------------+-----+--------------+--------------+------+ 
| 1 | what is your language? | 5 | manhattan |   0 | 2 | 
| 1 | what is your language? | 6 | cosmopolitan |   0 | 2 | 
| 2 | what is your drink? | 5 | manhattan |   0 | 2 | 
| 2 | what is your drink? | 6 | cosmopolitan |   0 | 2 | 
+-----+------------------------+-----+--------------+--------------+------+ 

Когда я хотел бы его, чтобы показать

mysql> select * from Questions, Answers where Answers.qId=2; 
+-----+------------------------+-----+--------------+--------------+------+ 
| qId | question    | aId | answer  | answer_count | qId | 
+-----+------------------------+-----+--------------+--------------+------+ 
| 2 | what is your drink? | 5 | manhattan |   0 | 2 | 
| 2 | what is your drink? | 6 | cosmopolitan |   0 | 2 | 
+-----+------------------------+-----+--------------+--------------+------+ 

Я я смотрел документацию в течение нескольких часов w и любая помощь будет очень благодарна :) Спасибо.

ответ

1

Ваш запрос должен быть;

SELECT * FROM Questions, Answers WHERE Answers.qId = 2 GROUP BY Answers.aId; 

или

SELECT * FROM Questions, Answers WHERE Answers.qId = Questions.qId and Questions.qId = 2; 

Этот запрос покажет вам это;

| qId |   question | aId |  answer | answer_count | qId | 
|-----|---------------------|-----|---------------|--------------|-----| 
| 2 | what is your drink? | 5 |  manhattan |   0 | 2 | 
| 2 | what is your drink? | 6 | cosmopolitan |   0 | 2 | 

и вы должны добавить эту ассоциацию;

Answer.belongsTo(Question, { 
    "constraints": true, 
    "foreignKey": 'qId' 
}); 

После того, как вы сможете использовать это отношение/присоединиться к этому;

Question 
    .findOne({ 
    "where": { 
     "qId": 2 
    }, 
    "include": [Answer] 
    }) 
    .then(function(question) { 
    // should show question with its answers 
    console.log(question); 

    // should show just answers of this question 
    console.log(question.Answers); 
    }); 
Смежные вопросы