gpt4 book ai didi

javascript - 如何在 sequelize findAll 方法中使用 left Join

转载 作者:行者123 更新时间:2023-12-03 22:26:29 26 4
gpt4 key购买 nike

我如何能够使用 sequelize findAll 来检查当前用户是否喜欢每个帖子。
where 查询过滤了 posts 数组对象。它需要检查当前用户是否喜欢某个帖子,但仍会获取所有数据。

我需要做左连接吗? where userId === req.session.user.id
Get all posts and check if user liked each post

我正在使用 sequelize 和 postgres。它几乎只是 sql 。

我应该如何使用 sequelize 实现这一目标

帖子结构是什么样的

enter image description here

以这段代码为例,这是我制作的laravel应用程序,我想在sequelize中实现相同的实现

php(示例)

public function getPosts( )
{
$posts = Post::with('user')
->with(['likes' => function ($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}])
->with(['comments' => function($query) {

$query->with('user');
}])->orderBy('created_at', 'desc')
->get();
$data = $posts->map(function(Post $post)
{
$user = auth()->user();
if($user->can('delete', $post)) {
$post['deletable'] = true;
}
if($user->can('update', $post)) {
$post['update'] = true;
}
// $comment = new Comment();
$post['likedByMe'] = $post->likes->count() == 0 ? false : true;
$post['likesCount'] = Like::where('post_id', $post->id)->get()->count();
$post['createdAt'] = $post->created_at->diffForHumans();
$post['createdAt'] = $post->updated_at->diffForHumans();

return $post;


});
return response()->json($data);
}

post.controller.js
 getPosts: async (req: any, res: Response) => {
// use async/await here
const posts = await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
// limit the likes based on the logged in user
{
model: models.Likes
}
],
order: [["createdAt", "DESC"]],
limit: 6
});
// i dont think this is the right approach.
posts.forEach(post => {
post.Likes.forEach(like => {
console.log(like.userId);
if (like.userId === req.session.user.id) {
post.setDataValue("likedByMe", true);
} else {
post.setDataValue("likedByMe", false);
}
});
});

return res.json(posts);

post.js
"use strict";
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
postContent: DataTypes.STRING,
liked: {
type: DataTypes.VIRTUAL,
allowNull: false,
defaultValue: false,
get: function () {
return this.getDataValue('Likes').length ? true : false;
}
},
likeCounts: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
validate: {
min: 0,
}
},
authorId: DataTypes.INTEGER
}, {});
Post.associate = function (models) {
Post.belongsTo(models.User, {
as: "author",
foreignKey: "authorId",
onDelete: "CASCADE"
});
Post.hasMany(models.Likes, {
foreignKey: "resourceId",
timestamps: false,
targetKey: "id",
onDelete: "CASCADE"
});
};
return Post;
};

最佳答案

我认为这个 forEach 语句有助于确定当前用户是否喜欢该帖子。

 getPosts: async (req: any, res: Response) => {
// use async/await here
const posts = await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
// limit the likes based on the logged in user
{
model: models.Likes
}
],
order: [["createdAt", "DESC"]],
limit: 6
});

posts.forEach(post => {
if (post.Likes.length === 0) {
post.setDataValue("likedByMe", false);
}
post.Likes.forEach(like => {
console.log(like.userId);
if (like.userId === req.session.user.id) {
post.setDataValue("likedByMe", true);
} else {
post.setDataValue("likedByMe", false);
}
});
});

return res.json(posts);
},

关于javascript - 如何在 sequelize findAll 方法中使用 left Join,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58682706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com