muayedward/ rateable-laravel
允许多个模型使用类似五星级系统进行评分。
3.1
2019-11-01 16:11 UTC
Requires
- php: >=7.0
- illuminate/database: ^5.5|^6.0|^6.1|^6.2|^6.3|^6.4|^6.5|^6.6
- illuminate/support: ^5.5|^6.0|^6.1|^6.2|^6.3|^6.4|^6.5|^6.6
Requires (Dev)
- phpunit/phpunit: 7.*|8.*
This package is not auto-updated.
Last update: 2024-09-29 06:14:18 UTC
README
为Laravel 5提供了一个特质,允许在您的应用程序中对任何Eloquent模型进行评分。
评分可以是五星级风格,也可以是简单的+1/-1风格。
安装
使用Composer安装此包
composer require muyaedward/rateable-laravel
与大多数Laravel包一样,如果您正在使用Laravel 5.5或更高版本,则该包将自动发现(如果您对此不熟悉,请了解更多信息)。
如果您正在使用5.5之前的Laravel版本,您需要注册Rateable 服务提供者。在您的config/app.php
中,将'muyaedward\Rateable\RateableServiceProvider'
添加到$providers
数组的末尾。
'providers' => [ Illuminate\Foundation\Providers\ArtisanServiceProvider::class, Illuminate\Auth\AuthServiceProvider::class, ... muyaedward\Rateable\RateableServiceProvider::class, ],
入门
在正确安装包之后,您需要生成迁移。
php artisan rateable:migration
它将生成<timestamp>_create_ratings_table.php
迁移。现在您可以使用artisan migrate命令运行它。
php artisan migrate
迁移后,将出现一个新表,名为ratings
。
用法
为了标记模型为“可评分”,导入Rateable
特质。
<?php namespace App; use muyaedward\Rateable\Rateable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Rateable; }
现在,您的模型可以访问一些额外的方法。
首先,为您的模型添加评分
$post = Post::first(); $rating = new muyaedward\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);