Node.js 续集和羽毛:当关系破裂时
在花了两天的时间试图弄明白为什么我的Sequelize模特们不致力于他们的关系之后,我决定是时候向你们大家征求意见了 故事是这样的 我正在使用Postgres(9.4)数据库编写Feathers JS应用程序,并使用Sequelize作为驱动程序。我在中运行了安装程序,经过一些劝说,我让迁移运行起来 据我所知,在使用Sequelize时必须特别考虑双向关系,因为如果Node.js 续集和羽毛:当关系破裂时,node.js,postgresql,sequelize.js,feathersjs,vorpal.js,Node.js,Postgresql,Sequelize.js,Feathersjs,Vorpal.js,在花了两天的时间试图弄明白为什么我的Sequelize模特们不致力于他们的关系之后,我决定是时候向你们大家征求意见了 故事是这样的 我正在使用Postgres(9.4)数据库编写Feathers JS应用程序,并使用Sequelize作为驱动程序。我在中运行了安装程序,经过一些劝说,我让迁移运行起来 据我所知,在使用Sequelize时必须特别考虑双向关系,因为如果ModelAreferencesModelB,ModelB必须已经定义,但是如果ModelBreferencesModelA…那么,
ModelA
referencesModelB
,ModelB
必须已经定义,但是如果ModelB
referencesModelA
…那么,我们会遇到一个依赖循环
这是因为依赖循环,文档说“使用这里描述的方法定义您的模型”。(好的,从技术上来说,它只是“假设”使用了这样的结构。另外,我只能发布2个链接,否则我会链接那个笨蛋。对此我很抱歉。)我在一个文档中发现了相同的结构
当然,我反映了所有这些(当然,除非我遗漏了一个小但重要的细节),但是……仍然没有骰子
以下是我所看到的:
迁移
迁移/create-accounts.js
迁移/create-users.js
psql
然后我启动了psql以查看引用是否正确:
databaseName=#\d账户
:
Referenced by:
TABLE "users" CONSTRAINT "users_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES accounts(id)
databaseName=#\d用户
:
Foreign-key constraints:
"users_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES accounts(id)
到目前为止还不错,对吧
让我们看看这个节目的模特部分
模型
src/models/account.js
src/models/user.js
src/models/index.js
齐心协力
src/app.js
为了简洁起见,我在app
中加载了很多模型,如下所示:
const models = require('./models')
app.use(compress())
// Lots of other statements
.configure(models);
测试
我一直在尝试制作一个用于更改密码、修改用户权限和其他实用程序任务的命令行实用程序,因此我采用了Vorpal(同样,只有2个链接,因此如果不熟悉,您必须自己查找——对不起)。以下是我的Vorpal程序的相关片段:
cli.js
啊
但是,如果我取消对User.findOne()
上方的行的注释,它就像一个符咒
为什么我必须在查询关系之前立即显式设置关系?为什么在用户模型的associate()方法中建立的关系(可能)没有保持不变?据我所知,它被调用了,而且是在正确的模型上。它是否以某种方式被推翻?由于某种奇怪的原因,app
,在用户模型中进行关联时是否与cli.js
中的不一样
我真的很困惑。非常感谢你们所能给予的任何帮助。我不知道为什么会这样,但我确实通过以下更改使其发挥了作用 src/models/index.js 我在导出函数末尾附近注释掉了以下区块:
Object.keys(sequelize.models).forEach(modelName => {
if ('associate' in sequelize.models[modelName]) {
sequelize.models[modelName].associate();
}
});
然后我将其移动到src/relate models.js
:
src/relate-models.js
在src/app.js
中,我调用了该函数并。。。普雷斯托改变了,成功了
src/app.js`
结束。如果有人能解释为什么以后做同样的事情会奏效,请告诉我,但现在…它奏效了
'use strict';
// account-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require('sequelize');
module.exports = function(app) {
// We assume we're being called from app.configure();
// If we're not, though, we need to be passed the app instance.
// Fair warning: I added this bit myself, so it's suspect.
if (app === undefined)
app = this;
const sequelize = app.get('sequelize');
// The rest of this is taken pretty much verbatim from the examples
const account = sequelize.define('account', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.STRING,
url_name: Sequelize.STRING,
}, {
paranoid: true,
timestamps: true,
classMethods: {
associate() {
const models = app.get('models');
this.hasMany(models['user'], {});
}
}
});
return account;
};
'use strict';
// user-model.js - A sequelize model
//
// See http://docs.sequelizejs.com/en/latest/docs/models-definition/
// for more of what you can do here.
const Sequelize = require('sequelize');
module.exports = function(app) {
// We assume we're being called from app.configure();
// If we're not, though, we need to be passed the app instance
if (app === undefined)
app = this;
const sequelize = app.get('sequelize');
const user = sequelize.define('user', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
accountId: {
type: Sequelize.INTEGER,
references: {
model: 'accounts', // Table name...is that right? Made the migration work...
key: 'id'
}
},
email: Sequelize.STRING,
[... curtailed for brevity ...]
}, {
// Are these necessary here, or just when defining the model to make a
// psuedo-migration?
paranoid: true, // soft deletes
timestamps: true,
classMethods: {
associate() {
const models = app.get('models');
// This outputs like I'd expect:
// Just to be sure...From the user model, models["account"]: account
console.log('Just to be sure...From the user model, models["account"]:', models['account']);
this.belongsTo(models['account'], {});
}
}
});
return user;
};
// I blatantly ripped this from both the following:
// https://github.com/feathersjs/generator-feathers/issues/94#issuecomment-204165134
// https://github.com/feathersjs/feathers-demos/blob/master/examples/migrations/sequelize/src/models/index.js
const Sequelize = require('sequelize');
const _ = require('lodash');
// Import the models
const account = require('./account');
const user = require('./user');
module.exports = function () {
const app = this;
// Note: 'postgres' is found in config/default.json as the db url
const sequelize = new Sequelize(app.get('postgres'), {
dialect: app.get('db_dialect'),
logging: console.log
});
app.set('sequelize', sequelize);
// Configure the models
app.configure(account);
app.configure(user);
app.set('models', sequelize.models);
// Set associations
Object.keys(sequelize.models).forEach(modelName => {
if ('associate' in sequelize.models[modelName]) {
sequelize.models[modelName].associate();
}
});
sequelize.sync();
// Extra credit: Check to make sure the two instances of sequelize.models are the same...
// Outputs: sequelize.models after sync === app.get("models")
// I've also run this comparison on sequelize and app.get('sequelize'); _.eq() said they also were identical
if (_.eq(sequelize.models, app.get('models')))
console.log('sequelize.models after sync === app.get("models")');
else
console.log('sequelize.models after sync !== app.get("models")');
};
const models = require('./models')
app.use(compress())
// Lots of other statements
.configure(models);
const vorpal = require('vorpal')();
const _ = require('lodash');
// Initialize app
// This seems a bit overkill since we don't need the server bit for this, but...
const app = require('./src/app');
const models = app.get('models');
// Get the models for easy access...
const User = models['user'];
const Account = models['account'];
// Run by issuing the command: node cli test
// Outputs to terminal
vorpal.command('test', 'A playground for testing the Vorpal environment.')
.action(function(args, callback) {
// User.belongsTo(Account); // <-- uncomment this and it works
User.findOne({ include: [{ model: Account }]}).then((user) => {
console.log("user.account.name:", user.account.name);
});
});
vorpal.show().parse(process.argv);
Just to be sure...From the user model, models["account"]: account
sequelize.models after sync === app.get("models")
connect:
Unhandled rejection Error: account is not associated to user!
at validateIncludedElement (/vagrant/node_modules/sequelize/lib/model.js:550:11)
at /vagrant/node_modules/sequelize/lib/model.js:432:29
at Array.map (native)
at validateIncludedElements (/vagrant/node_modules/sequelize/lib/model.js:428:37)
at .<anonymous> (/vagrant/node_modules/sequelize/lib/model.js:1364:32)
at tryCatcher (/vagrant/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/vagrant/node_modules/bluebird/js/release/promise.js:504:31)
at Promise._settlePromise (/vagrant/node_modules/bluebird/js/release/promise.js:561:18)
at Promise._settlePromise0 (/vagrant/node_modules/bluebird/js/release/promise.js:606:10)
at Promise._settlePromises (/vagrant/node_modules/bluebird/js/release/promise.js:685:18)
at Async._drainQueue (/vagrant/node_modules/bluebird/js/release/async.js:138:16)
at Async._drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:148:10)
at Immediate.Async.drainQueues (/vagrant/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:574:20)
at tryOnImmediate (timers.js:554:5)
at processImmediate [as _immediateCallback] (timers.js:533:5)
Object.keys(sequelize.models).forEach(modelName => {
if ('associate' in sequelize.models[modelName]) {
sequelize.models[modelName].associate();
}
});
/**
* This is workaround for relating models.
* I don't know why it works, but it does.
*
* @param app The initialized app
*/
module.exports = function(app) {
const sequelize = app.get('sequelize');
// Copied this from src/models/index.js
Object.keys(sequelize.models).forEach(modelName => {
if ('associate' in sequelize.models[modelName]) {
sequelize.models[modelName].associate();
}
});
}
const models = require('./models')
app.use(compress())
// Lots of other statements
.configure(models);
require('./relate-models')(app);