zhenhai/laravel-rateable

允许多个模型使用类似五星级评分系统进行评分。

1.0.5 2017-01-21 08:30 UTC

This package is not auto-updated.

Last update: 2024-09-23 14:39:03 UTC


README

Build Status SensioLabsInsight Latest Stable Version License

Total Downloads Monthly Downloads Daily Downloads

为Laravel 5提供特性,允许在您的应用中对多个模型进行评分。

评分可以是五星级风格,也可以是简单的+1/-1风格。

安装

编辑您的项目 composer.json 文件,以要求 willvincent/laravel-rateable

"require": {
  "willvincent/laravel-rateable": "~1.0"
}

接下来,从终端更新Composer。

composer update

与大多数Laravel包一样,您需要注册 Rateable 服务提供者。在您的 config/app.php 中,将 'willvincent\Rateable\RateableServiceProvider' 添加到 $providers 数组的末尾。

'providers' => [

    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    ...
    willvincent\Rateable\RateableServiceProvider::class,

],

入门

在包正确安装后,您需要生成迁移。

php artisan rateable:migration

它将生成 <timestamp>_create_ratings_table.php 迁移。您现在可以使用 artisan migrate 命令运行它

php artisan migrate

迁移后,将出现一个新的表,ratings

使用方法

您需要在您的模型上设置它是否可评分。

<?php namespace App;

use willvincent\Rateable\Rateable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

    use Rateable;

}

现在,您的模型可以访问一些额外的功能。

首先,向您的模型添加评分

$post = Post::first();

$rating = new willvincent\Rateable\Rating;
$rating->rating = 5;
$rating->user_id = \Auth::id();

$post->ratings()->save($rating);

dd(Post::first()->ratings);

一旦模型有一些评分,您可以获取平均评分

$post = Post::first();

dd($post->averageRating);
// $post->averageRating() also works for this.

您还可以获取评分百分比。这也是如何强制最大评分值的方法。

$post = Post::first();

dd($post->ratingPercent(10)); // Ten star rating system
// Note: The value passed in is treated as the maximum allowed value.
// This defaults to 5 so it can be called without passing a value as well.

// $post->ratingPercent(5) -- Five star rating system totally equivilent to:
// $post->ratingPercent()

您还可以获取给定可评分项目的评分总和或平均值,当前(授权)已投票/评分。

$post = Post::first();

// These values depend on the user being logged in,
// they use the Auth facade to fetch the current user's id.


dd($post->userAverageRating); 

dd($post->userSumRating);