我将如何使用sequelize findAll来检查当前用户是否喜欢每个帖子。
where
查询通过posts数组对象进行过滤。它需要检查当前用户是否喜欢某个帖子,但仍获取所有数据。
我需要左联接吗? where
userId === req.session.user.id
Get all posts and check if user liked each post
我正在使用sequelize和postgres。它几乎只是sql。
我应该如何使用续集来实现这一目标
帖子结构是什么样的
以这段代码为例,这是我制作的laravel应用,我希望在续集中实现相同的实现
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;
};
答案 0 :(得分:0)
我认为此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);
},