jimchen / laravel-vote
该包帮助您将基于用户的投票系统添加到模型中
v1.0.0
2021-05-20 03:26 UTC
Requires
- php: >=7.2
- laravel/framework: ^5.5|~6.0|~7.0|~8.0
- symfony/polyfill-php80: ^1.22
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.18
- mockery/mockery: ^1.3
- orchestra/testbench: ^3.5|~4.0|~5.0|~6.0
- phpstan/phpstan: ^0.12.81
This package is auto-updated.
Last update: 2024-09-21 08:37:07 UTC
README
🎉 此包帮助您将基于用户的投票系统添加到模型中。
从 jcc/laravel-vote 分支而来
安装
您可以使用 Composer 安装此包
$ composer require "jimchen/laravel-vote"
然后将服务提供者添加到 config/app.php
JimChen\LaravelVote\VoteServiceProvider::class
发布迁移文件
$ php artisan vendor:publish --provider="JimChen\LaravelVote\VoteServiceProvider" --tag="migrations"
最后,在 User 模型中使用 VoteTrait
use JimChen\LaravelVote\Traits\Voter; class User extends Model { use Voter; }
或者在使用 Comment 模型时使用 CanBeVoted
use JimChen\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); }