kikis/vote-system

此包帮助您向模型添加基于用户的投票系统

dev-main 2022-10-27 13:45 UTC

This package is auto-updated.

Last update: 2024-09-27 18:32:11 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