samuelsihotang1 / laravel-vote
此包帮助您将基于用户的投票系统添加到您的模型中,源自 jcc/laravel-vote
dev-master
2023-07-24 08:17 UTC
Requires
- php: >=7.2
- laravel/framework: ^5.5|~6.0|~7.0|^8.83.27|~9.0|^10.0
- symfony/polyfill-php80: ^1.27
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.19.3
- mockery/mockery: ^1.6.4
- orchestra/testbench: ^3.5|~4.0|~5.0|^6.28
- phpstan/phpstan: ^0.12.100
This package is auto-updated.
Last update: 2024-09-24 10:38:36 UTC
README
🎉 此包帮助您将基于用户的投票系统添加到您的模型。
安装
您可以使用Composer安装此包
$ composer require "samuelsihotang1/laravel-vote:~2.0"
然后,将服务提供者添加到 config/app.php
samuelsihotang1\LaravelVote\VoteServiceProvider::class
发布迁移文件
$ php artisan vendor:publish --provider="samuelsihotang1\LaravelVote\VoteServiceProvider" --tag="migrations"
最后,在User模型中使用VoteTrait
use samuelsihotang1\LaravelVote\Traits\Voter; class User extends Model { use Voter; }
或者,在Comment模型中使用CanBeVoted
use samuelsihotang1\LaravelVote\Traits\Votable; class Comment extends Model { use Votable; }
使用方法
对于User模型
对评论或评论进行点赞
$comment = Comment::find(1); $user->upVote($comment);
对评论或评论进行踩
$comment = Comment::find(1); $user->downVote($comment);
取消对评论或评论的投票
$comment = Comment::find(1); $user->cancelVote($comment);
获取用户已投票的评论项
$user->getVotedItems(Comment::class)->get();
检查用户是否进行了点赞或踩
$comment = Comment::find(1); $user->hasVoted($comment);
检查用户是否进行了点赞
$comment = Comment::find(1); $user->hasUpVoted($comment);
检查用户是否进行了踩
$comment = Comment::find(1); $user->hasDownVoted($comment);
对于Comment模型
获取评论的投票者
$comment->voters()->get();
统计评论的投票者数量
$comment->voters()->count();
获取评论的点赞者
$comment->upVoters()->get();
统计评论的点赞者数量
$comment->upVoters()->count();
获取评论的踩者
$comment->downVoters()->get();
统计评论的踩者数量
$comment->downVoters()->count();
检查是否被投票
$user = User::find(1); $comment->isVotedBy($user);
检查是否被点赞
$user = User::find(1); $comment->isUpVotedBy($user);
检查是否被踩
$user = User::find(1); $comment->isDownVotedBy($user);
N+1问题
为了避免N+1问题,您可以使用预加载来将此操作减少到仅2个查询。在查询时,您可以使用with
方法指定应该预加载哪些关系
// Voter $users = User::with('votes')->get(); foreach($users as $user) { $user->hasVoted($comment); } // Votable $comments = Comment::with('voters')->get(); foreach($comments as $comment) { $comment->isVotedBy($user); }