私が理解しようとしているところでは、どのように続行が熱心な読み込みをしているのか、それがなぜ私にとってうまくいかないのですか?Sequelizeでの熱意のある関連付けの問題の理解
私はコマンドを移行sequelizeを経由して、次の表を作成し、想定してください:
ユーザーテーブル:
return queryInterface.createTable('Users', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
.... other columns
}
アイテム表:
return queryInterface.createTable('Items', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
insertUserId: {
allowNull: false,
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'insertUserId'
}
},
..... some other columns
}
アイテムモデル(この関連付けを完全に動作します):
module.exports = (sequelize, DataTypes) => {
const Item = sequelize.define('Item', {
.... configuration of columns
});
Item.associate = (models) => {
Item.belongsTo(models.User, {
as: 'insertUser'
});
};
Item.associate = (models) => {
Item.belongsTo(models.User, {
as: 'editUser'
});
return Item;
};
ユーザーモデルは、(それは私のためのトリッキーな部分です):
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
.... configuration of columns
});
User.associate = (models) => {
- TRICKY ASSOCIATION -
};
return User;
};
私の目標:私はitemControllerに含まれ、ユーザーとのすべてのアイテムを取得したい
(私はすべてのユーザーを取得し、関連するすべての項目をuserController(LEFT JOIN、右?)に含めたいと思っています。私は、ユーザーモデルで、次を試してみました
{
id: '0',
name: 'username',
insertedItems: [
{ <item_1> },
{ <item_n> }
]
}
UserControllerで
function getUsersItems(year) {
return User.findAll({
include: [{
model: Item,
as: 'insertedItems'
}],
attributes: ['id', 'name']
});
}
:イーガーローディングは(?私は右だ)
は出力を望んでいたことを行うことができています
User.associate = (models) => {
User.hasMany(models.Item, {
as: 'insertedItems',
foreignKey: 'id'
});
};
ドキュメントを正しく理解しているので、ここでは 'hasMany'が適切です。エイリアスも重要です( 'insertedItems')。何か、私は行方不明でしたか?
私はsequelize 4.15.0とnodejs 9.2.0を使用しています。
ありがとうございました