用户 我有一个端点可以为应用程序中的帖子添加“赞”。端点获取单击“点赞”按钮的用户的 ID,并将该 ID 以及点赞数(现在不重要)插入数据库中。为此,我首先使用此代码获得帖子的所有点赞:
const likes = await strapi.db.query("api::post.post").findOne({
where: {id: postId},
populate: [
"likes"
]
});
这会返回类似这样的内容(不完全是,但我提取这部分以在端点中使用):
[
{ id: 8, no_of_likes: 21 },
{ id: 10, no_of_likes: 13 },
{ id: 11, no_of_likes: 16 }
]
现在用push向这个数组添加一个新条目,这给了我一个新的json数组,如下所示:
[
{ id: 8, no_of_likes: 21 },
{ id: 10, no_of_likes: 13 },
{ id: 11, no_of_likes: 16 },
{ id: 2, no_of_likes: 22 }
]
现在我用这个新数组更新数据库的 Likes 字段,如下所示:
//Add user to the liked_by section.
const entry = await strapi.entityService.update("api::post.post", postId, {
data: {
likes: likesJsonObject
}
});
但这会返回错误“likes 中提供的某些组件与实体无关”,即使 id 2 绝对存在于我的用户中。如果我通过 Strapi 内容管理器手动添加相同的注册表({id:2,no_of_likes:21}),它就会起作用,并且插入与我想要插入的内容完全相同的内容。我如何通过端点以编程方式完成此操作?
这不是为帖子点赞的最佳解决方案,通常我会建议创建一个包含以下内容的集合:
// api::post-like.post.like
{
user: Relation => to user
post: Relation => to post
}
因此,要使当前的实现正常工作,您必须从 json 中排除
component
ids
。 Strapi 的工作方式是在编辑时重新创建组件:
const components = [
{ id: 8, no_of_likes: 21 },
{ id: 10, no_of_likes: 13 },
{ id: 11, no_of_likes: 16 },
{ id: 2, no_of_likes: 22 }
].map(({id, ...component}) => ({...component}))
然后
const entry = await strapi.entityService.update("api::post.post", postId, {
data: {
likes: components,
}
});
应该可以工作