如何使sequelize在视图中有许多关联小写
Posted
技术标签:
【中文标题】如何使sequelize在视图中有许多关联小写【英文标题】:How to make sequelize has many association lowercase in views 【发布时间】:2016-09-15 09:35:48 【问题描述】:这里一切正常。唯一的问题是,在我的车把文件中,我必须像这样处理一个人的任务:
this.Tasks
我希望它看起来像这样:
this.tasks
我将如何自定义 Sequelize 来做到这一点?
这就是我的应用程序的根路径的样子(它正在呈现 index.handlebars 文件)
我的路线:
router.get('/', function(req, res)
models.Person.findAll(
include: [ models.Task ]
).then(function(people)
res.render('index',
user_id: req.session.user_id,
email: req.session.user_email,
logged_in: req.session.logged_in,
people: people
);
);
);
我的 index.handlebars 文件:
#each people
<li>
this.name
#if ../logged_in
<a href="/people/this.id/destroy"> destroy</a>
/if
<ul>
#if ../logged_in
<li>
<form action="/people/this.id/tasks/create" method="POST" style="display: inline">
<input type="text" name="task" placeholder="add task here">
<input type="submit" value"assign task">
</form>
</li>
/if
#each this.Tasks
<li>
this.task
#if ../../logged_in
<a href="/people/this.person_id/tasks/this.id/destroy">destroy</a>
/if
</li>
/each
</ul>
</li>
/each
我的人员表迁移:
"use strict";
module.exports =
up: function(queryInterface, Sequelize)
return queryInterface
.createTable('people',
id:
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
,
name: Sequelize.STRING,
created_at: Sequelize.DATE,
updated_at: Sequelize.DATE
);
,
down: function(queryInterface, Sequelize)
return queryInterface
.dropTable('people');
;
我的任务表迁移:
"use strict";
module.exports =
up: function(queryInterface, Sequelize)
return queryInterface
.createTable('tasks',
id:
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true
,
person_id:
type: Sequelize.INTEGER
,
task: Sequelize.STRING,
created_at: Sequelize.DATE,
updated_at: Sequelize.DATE
);
,
down: function(queryInterface, Sequelize)
return queryInterface
.dropTable('tasks');
;
我的 person.js 模型:
"use strict";
module.exports = function(sequelize, DataTypes)
var Person = sequelize.define("Person",
name: DataTypes.STRING
,
underscored: true,
freezeTableName: true,
tableName: 'people',
classMethods:
associate: function(models)
Person.hasMany(models.Task)
);
return Person;
;
我的 task.js 模型:
"use strict";
module.exports = function(sequelize, DataTypes)
var Task = sequelize.define("Task",
task: DataTypes.STRING
,
freezeTableName: true,
tableName: 'tasks',
classMethods:
associate: function(models)
Task.belongsTo(models.Person,
onDelete: "CASCADE",
foreignKey:
allowNull: false
);
);
return Task;
;
【问题讨论】:
【参考方案1】:您也可以使用“as”选项通过别名来设置名称,而不是使用小写名称来表示 sequelize.define。前任。 Task.belongsTo(models.Person, as: 'task');
。或者,您可以在定义函数本身中设置别名。前任。
sequelize.define("Task", attributes,
name :
singular: "task",
plural: "tasks"
)
【讨论】:
【参考方案2】:将小写的模型名称定义为
var Task = sequelize.define("task",
【讨论】:
【参考方案3】:我的 task.js 模型:
module.exports = function(sequelize, DataTypes) var Task = sequelize.define("Task",
只要指定
var task = sequelize.define("task",
它没有解决你的问题吗?
【讨论】:
以上是关于如何使sequelize在视图中有许多关联小写的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Sequelize Postgres 中使用小写函数