我的应用程序中有一个功能,可充当博客文章的活动供稿(类似于Tumblr)。在此页面的路由中,我的主要查询在我的博客文章表中,并且我正在将包含其他元信息和注释的表加入该表,以获取每个博客文章的功能齐全的卡片。这些表来自我的类别(对帖子进行分类),主题(感兴趣的主题),附加的文件(文件/图像)和评论(对帖子进行评论)表。
使用当前查询,我可以毫无问题地连接所有这些表,但是我遇到了与博客帖子上的父查询关联的where子句的问题。将file和comment表连接在一起时,会发生子查询,我认为这与博客文章和那些表之间的关联类型有关,并以某种方式影响结果。
提供的是架构和关联:
blog_post
社团协会
用户
类别
社团协会
话题
社团协会
文件和注释表在其架构文件中没有与此问题相关的关联。
提供查询(请不要使用驼峰式别名作为上面的别名列名称)
models.BlogPost.findAll({
order: 'Date DESC',
include: [{
model: models.User,
where: { organizationId: req.user.organizationId },
attributes: ['userId', 'firstName', 'lastName'],
required: false,
},
{
model: models.Topic,
attributes: ['topic'],
required: false
},
{
model: models.Category,
attributes: ['category'],
required: false
},
{
model: models.File,
attributes: ['file'],
required: false
},
{
model: models.Comment,
include: [{
model: models.User,
attributes: ['userId','firstName', 'lastName']
}],
required: false
}],
limit: 10
})
Run Code Online (Sandbox Code Playgroud)
带有子查询的UPDATE:
SELECT `blog_post`.*, `user`.`user_id`, `user`.`first_name`, `user`.`last_name`, `topic`.`topic_id`, `topic`.`topic`, `category`.`category_id`, `category`.`category_name`, `file`.`file_id`, `file`.`file`, `comment`.`comment_id`, `comment`.`comment`, `comment`.`blog_id`, `comment`.`user_id`, `comment`.`created_at`, `comment`.`updated_at`, `comment`.`blog_id`, `comment`.`user_id`, `comment.user`.`user_id`
FROM (SELECT `blog_post.`blog_id`, `blog_post.`date`, `blog_post.`title`, `blog_post.`content`, `blog_post.`topic_id`, `blog_post.`category_id`, `blog_post.`user_id`, `blog_post.`created_at`, `blog_post.`updated_at`, `blog_post.`user_id`, `blog_post.`topic_id`, `blog_post.`category_id` FROM `blog_post LIMIT 10) AS `blog_post
LEFT OUTER JOIN `user` AS `user` ON `blog_post.`user_id` = `user`.`user_id` AND `user`.`organization_id` = 1
LEFT OUTER JOIN `topic` AS `topic` ON `blog_post.`topic_id` = `topic`.`topic_id`
LEFT OUTER JOIN `category` AS `category` ON `blog_post.`category_id` = `category`.`category_id`
LEFT OUTER JOIN `file` AS `file` ON `blog_post.`blog_id` = `file`.`blog_id`
LEFT OUTER JOIN `comment` AS `comment` ON `blog_post.`blog_id` = `comment`.`blog_id`
LEFT OUTER JOIN `user` AS `comment.user` ON `comment`.`user_id` = `comment.user`.`user_id`
ORDER BY date DESC;
Run Code Online (Sandbox Code Playgroud)
您可能需要添加方法subQuery: false的options对象findAll。但是,此选项在sequelize文档中不存在,您可以在中找到它source code。如果未设置,则默认为,true并导致LIMIT在查询中存在该选项时添加您提到的子查询。
| 归档时间: |
|
| 查看次数: |
1451 次 |
| 最近记录: |