如何在laravel 5中修复多个投票? 用户1可以喜欢这个帖子,再次登录后用户1可以再次投票/喜欢。我希望用户1只能投票/喜欢一次。怎么解决? 这是我的代码:
在此用户模型中
public function hasVotesPost(Posts $posts){
return (bool) $posts->votes
->where('user_id', $posts->id)
->where('vote', get_class($posts))
->count() ;
}
在此控制器中
public function getVotes($post_id){
$post_id = posts::find($post_id);
if(!$post_id){
return redirect()->route('/');
}
if(Auth::user()->hasVotesPost($post_id)){
return redirect()->back();
}
$votes = $post_id->votes()->create([]);
Auth::user()->votes()->save($votes);
return redirect()->back();
}
答案 0 :(得分:0)
好吧,我假设投票只存储在一列中并且只是递增,所以首先需要的是一个带有外键的数据透视表形式的post和user表。所以指出一个create posts_users (post_id, user_id)
表。
第二件事是定义帖子和用户之间的关系。
发布模型
public function users()
{
return $this->belongsToMany('User', 'posts_users ', 'post_id', 'user_id');
}
更改在此
上存储投票数据的方式$post->users()->attach($user_id);
检查用户是否对特定帖子投了赞功能
function didUserVoteOnPost($user_id, $post_id)
{
$post = Post::where('id', '=', $post_id)->with(['user' => function($query) use($user_id){
$query->where('user_id', '=' , $user_id);
}]);
if(!empty($post->pivot)) return true;
return false;
}
我没有测试它,所以你需要自己搞清楚bug。