jcc/laravel-vote

该包帮助您将基于用户的投票系统添加到您的模型中

v2.0.0 2021-03-14 07:29 UTC

This package is auto-updated.

Last update: 2024-09-07 07:17:12 UTC


README

🎉 此包帮助您将基于用户的投票系统添加到您的模型中。

安装

您可以使用 Composer 安装此包

$ composer require "jcc/laravel-vote:~2.0"

然后将服务提供者添加到 config/app.php

Jcc\LaravelVote\VoteServiceProvider::class

发布迁移文件

$ php artisan vendor:publish --provider="Jcc\LaravelVote\VoteServiceProvider" --tag="migrations"

最后,在 User 模型中使用 VoteTrait

use Jcc\LaravelVote\Traits\Voter;

class User extends Model
{
    use Voter;
}

或在 Comment 模型中使用 CanBeVoted

use Jcc\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);
}

事件

参考

许可证

MIT