質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

Q&A

0回答

1160閲覧

へんこうなしsequelizeでアソシエーションエラー(SequelizeEagerLoadingError)になる

hokosugi

総合スコア63

Node.js

Node.jsとはGoogleのV8 JavaScriptエンジンを使用しているサーバーサイドのイベント駆動型プログラムです。

Express

ExpressはNode.jsのWebアプリケーションフレームワークです。 マルチページを構築するための機能セットおよびハイブリッドのWebアプリケーションを提供します。

0グッド

0クリップ

投稿2021/04/11 01:29

編集2021/04/11 01:33

sequelizeで生成したmodelファイルに書いたアソシエーションがエラーになる。

node.js: v11.6.0
express: 4.16.1

やってみたこと
  1. sequelizeのドキュメントにあるExtending Model and calling init(attributes, options)タイプでは同じエラーがでたのでdefineタイプに変更
  2. 生成モデルファイルにデフォで引数になっているmodelsを確認したいがコンソールに表示されず
  3. モデルファイル(user.js, friends.js)をそれぞれのファイルに値を渡してアソシエーションしてみる => 変わらず
  4. ドキュメントにあるサンプルをコピペ(controller2.js)して実行 => 正常

モデルのファイルに書いてあるUser.associateの値が間違えているように感じますが、ここから先がどうやればよいかわかりません。

お知恵を拝借したいです。宜しくおねがいします。

(node:4587) UnhandledPromiseRejectionWarning: SequelizeEagerLoadingError: friends is not associated to User!
/* controller.js */ const express = require('express'); const mysql = require('mysql2'); require('dotenv').config(); const { Sequelize, DataTypes, Model } = require('sequelize'); const User = require('./db/models/user'); const friends = require('./db/models/friends'); const app = express(); const port = process.env.PORT; const sequelize = new Sequelize('sample', 'sample', 'password', { host: '127.0.0.1', dialect: 'mysql' }); async function connect(){ try { await sequelize.authenticate(); console.log('Connection has been established successfully.'); } catch (error) { console.error('Unable to connect to the database:', error); }; const usr = await User(sequelize, DataTypes); const fd = await friends(sequelize, DataTypes); console.log('fn start') console.dir(usr.associate); //[AsyncFunction] console.log('end fn'); // SequelizeEagerLoadingError: friends is not associated to User! const usrFriend = await usr.findOne({ where: { id: 1 }, // Fetching a single associated element include: fd }); console.log('userFriend:'+ usrFriend); console.log('userFriends.email:'+usrFriend.friends.email);//リレーション } connect(); app.listen(8000, () => { console.log(`Example app listening at http://localhost:${port}`); });
/* models/user.js */ 'use strict'; const { Model } = require('sequelize'); const friends = require('./friends'); module.exports = async (sequelize, DataTypes) => { // 以下36行目まではmode:generateで生成されたModelタイプ(ドキュメントにアソシエーションのサンプルがなく、検索でも見つからないため)から変更、 *42行目以下参照 var User = sequelize.define('User', { firstName: { type: DataTypes.STRING, allowNull: true, }, lastName: { type: DataTypes.STRING, allowNull: true }, email: { type: DataTypes.STRING, allowNull: true }, line_id: { type: DataTypes.STRING, allowNull: true }, createdAt: DataTypes.DATE, updatedAt: DataTypes.DATE }, {}); User.associate = async function(models) { // 以下2行は自作 //const fd = await friends(sequelize, DataTypes); //User.hasMany(fd, {foreignKey: 'userId'}); //console.dir(models); //[node controller.js]実行してもコンソールに表記されないので、modelsが有効かどうかわからない //こちらのサイトを参考にして https://blog.kozakana.net/2018/04/sequelize_join/ models.User.hasMany(models.friends, {foreignKey: 'userId'}) }; await User.sync() return await User; }; //自動生成されるの以下の形式 // class User extends Model {} // User.init({ // // Model attributes are defined here // firstName: { // type: DataTypes.STRING, // allowNull: false // }, // lastName: { // type: DataTypes.STRING // // allowNull defaults to true // } // } // })
/* models/friends.js */ 'use strict'; const { Model } = require('sequelize'); const User = require('./user'); module.exports = async (sequelize, DataTypes) => { var friends = sequelize.define('friends', { sourceS3: { type: DataTypes.STRING, allowNull: true, }, line_id: { type: DataTypes.STRING, allowNull: true }, email: { type: DataTypes.STRING, allowNull: true }, userId: { type: DataTypes.INTEGER }, createdAt: DataTypes.DATE, updatedAt: DataTypes.DATE }, {}); friends.associate = async function(models) { //friends.belongsTo(await User(sequelize, DataTypes)); models.friends.belongsTo(models.User); }; await friends.sync() return await friends; };
/* controller2.js */ require('dotenv').config(); const { Sequelize, DataTypes, Model } = require('sequelize'); const sequelize = new Sequelize('sample', 'sample', 'password', { host: '127.0.0.1', dialect: 'mysql' }); const Member = sequelize.define('member', { name: DataTypes.STRING }, { timestamps: false }); const Job = sequelize.define('job', { name: DataTypes.STRING }, { timestamps: false }); const Machine = sequelize.define('machine', { name: DataTypes.STRING, size: DataTypes.STRING }, { timestamps: false }); Member.hasMany(Job); Job.belongsTo(Member); Member.hasMany(Machine, { as: 'Instruments' }); async function sample(){ await Member.sync(); await Job.sync(); await Machine.sync(); const tasks = await Job.findAll({ include: Member }); console.log("Json:" + JSON.stringify(tasks, null, 2)); } sample(); // 結果 データ入力なしなので空Jsonだけど正常に終了 // Executing (default): SELECT `job`.`id`, `job`.`name`, `job`.`memberId`, `member`.`id` AS `member.id`, `member`.`name` AS `member.name` FROM `jobs` AS `job` LEFT OUTER JOIN `members` AS `member` ON `job`.`memberId` = `member`.`id`; Json:[]

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問