我正在尝试在Laravel项目中创建一个关于喜欢和不喜欢的API请求:
Route :: post('like','Api \ ApiController @ like');
ApiController中的函数如下:
$post = \App\Post::find($request->id);
$social = SocialPost::where([['user_id', '=', ($request->user_id)],['post_id', '=', ($request->id)]])->first();
$unsocial = SocialPost::where([['user_id', '=', ($request->user_id)],['post_id', '=', ($request->id)],['like', '=', 0]])->first();
if ($social) {
if ($unsocial) {
$social->update(['like' => 1]);
return json_encode(array('status' => true,'msg'=>'like'));
}
else {
$social->update(['like' => 0]);
return json_encode(array('status' => true,'msg'=>'dislike'));
}
}
else {
$join = new \App\SocialPost;
$join->user_id = $request->user_id;
$join->post_id = $post->id;
$join->like = 1;
$join->view = 0;
$join->creator = 1;
$join->save();
return json_encode(array('status' => true,'msg'=>'New table'));
}
问题在于第一个If语句有效,而第二个if语句无效。如果该行已经存在,那么即使返回的消息是“不喜欢”,他也始终将“喜欢”设置为“ 1”。
答案 0 :(得分:0)
这是一个适合您的示例。
<?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]);
说明
您可以使用文档here中引用的firstOrCreate
确定是否存在SocialPost记录,或创建一个新记录。第一个数组参数包含您要查找的内容,第二个数组参数包含如果第一个参数未显示任何内容应创建的内容
// 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],
);
然后,您可以使用文档here中引用的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);
}