我想要使用laravel在此线程帖子中得到与答案相同的实现。
Get all posts and check if user liked each post
我正在使用sequelize和postgres。它几乎只是sql。
现在,我从用户那里获取所有帖子,但我希望所有帖子,而不仅仅是当前用户,并且我希望findAll检查当前用户是否喜欢每个帖子。
我应该如何使用续集来实现这一目标
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"] },
{
model: models.Likes,
required: false,
where: { userId: req.session.user.id }
}
],
order: [["createdAt", "DESC"]],
limit: 6
});
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;
};