[英]Query Node.js , Sequelize and Mysql
I need to query two tables in a Node.js project.我需要查询 Node.js 项目中的两个表。 The project uses Sequelize and Mysql.该项目使用 Sequelize 和 Mysql。
When a user registers a post in 'postagens table', he records the email.当用户在“postagens table”中注册帖子时,他会记录电子邮件。 When accessing the view, I need to consult the user's full name in 'users table' and load it into the view.访问视图时,我需要在“用户表”中查询用户的全名并将其加载到视图中。
<td> {{fullname}} </td>
What change should I make in 'app.js'?我应该在“app.js”中做哪些改变?
Very thanks!很感谢!
//app.js //app.js
app.get('/', function (req, res) {
Post.findAll({ raw: true, where: {
companyid: '3',
enviado: '0'
} }).then(function (posts) {
res.render('home', { posts: posts });
});
});
//home.handlebars //home.handlebars
<div class="card">
<div class = "card-body">
<h1>Lista de Posts</h1>
<form class="new-post" action="/cad" method="get">
<button class="btn btn-success" type="submit">Nova Postagem!</button>
</form>
<table class="table" width= 100%>
<thead>
<td>id</td>
<td>Título</td>
<td>Conteúdo</td>
<td>Fullname</td>
<td>Ações</td>
</thead>
<tbody>
{{#each posts}}
<tr>
<td>{{id}}</td>
<td>{{titulo}}</td>
<td>{{conteudo}}</td>
<td>{{fullname}}</td>
<td>
<form class="form-action" action="/edit/{{id}}" method="get">
<button class="btn btn-success" type="submit">edit</button>
</form>
</td>
<td>
<form class="form-action" action="/deletar/{{id}}" method="get">
<button class="btn btn-success" type="submit">delete</button>
</form>
</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
//table postagens //表邮资
CREATE TABLE `postagens` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`titulo` VARCHAR(255) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`conteudo` TEXT NULL COLLATE 'latin1_general_ci',
`companyid` TEXT NULL COLLATE 'latin1_general_ci',
`enviado` TEXT NULL COLLATE 'latin1_general_ci',
`email` TEXT NULL COLLATE 'latin1_general_ci',
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=51
;
//table users //表用户
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`email` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`password` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`fullname` VARCHAR(255) NOT NULL COLLATE 'utf8mb4_unicode_ci',
`createdAt` DATETIME NOT NULL,
`updatedAt` DATETIME NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='utf8mb4_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4
;
您需要调用 users.findOne 或 users.findByPk 并且您需要传递要在请求中显示的用户的 id 字段...但是至于对您的应用程序文件的更改,我不太确定我知道那里发生了什么......你总是让它调用一个查询......如果你的节点服务器上有类似 apollo graphql 的东西,那么你只需传递一个查询......你需要某种方式来向你展示想要调用 diff sequelize 查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.