1 回答
TA贡献1794条经验 获得超7个赞
这是一个应该与您一起使用的示例。
<?php
// Get the post from the database
$post = \App\Post::find($request->id);
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
// Declare an empty variable that will determine if
// the post is being "liked" or "disliked"
$postAction = '';
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// The post has at least 1 like
$postAction = 'dislike';
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// The post has 0 likes
$postAction = 'like';
// Increment the likes by 1
$socialPost->increment('likes', 1);
}
// Determine if this was a new SocialPost record
if ($socialPost->wasRecentlyCreated)
{
// Override the post action as "New table"
$postAction = 'New table';
}
// Return the goods
return json_encode(['status' => true, 'msg' => $postAction]);
解释
您可以确定 SocialPost 记录是否存在,或创建一个新记录 - 使用此处firstOrCreate文档中引用的全部在一行中。第一个数组参数接受您要查找的内容,第二个数组参数接受如果第一个参数没有出现则应创建的内容
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
然后,您可以通过使用increment或decrement在此处的文档中引用来清理加减点赞。
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// Increment the likes by 1
$socialPost->increment('likes', 1);
}
- 1 回答
- 0 关注
- 138 浏览
添加回答
举报