主页/PHP笔记/PHP问答/框架Laravel/Laravel + Eloquent:如何构建评分系统

Laravel + Eloquent:如何构建评分系统

Bug编译狮

Bug编译狮

标题:Laravel + Eloquent 构建评分系统

评分系统是许多应用中的重要组成部分,例如在线评论、游戏排行榜等。在 Laravel 和 Eloquent 中,我们可以轻松地实现这个功能。以下是一个简单的示例,展示如何创建一个评分表,并使用 Eloquent 进行数据操作。

1. 创建评分表模型

首先,我们需要创建一个评分表的模型。假设我们有一个名为 Rating 的表,其中包含用户 ID、产品 ID 和评分值三个字段。

php artisan make:model Rating

然后,在 app/Models/Rating.php 文件中定义模型:

namespace AppModels;

use IlluminateDatabaseEloquentModel;

class Rating extends Model
{
    protected $fillable = ['user_id', 'product_id', 'score'];
}

2. 创建评分表迁移

接下来,我们需要创建一个数据库迁移文件来创建 Rating 表。

php artisan make:migration create_ratings_table --create=ratings

在生成的迁移文件中,添加以下代码:

public function up()
{
    Schema::create('ratings', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('user_id');
        $table->unsignedBigInteger('product_id');
        $table->integer('score')->nullable();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('ratings');
}

运行迁移:

php artisan migrate

3. 创建评分表控制器

现在,我们需要创建一个控制器来处理评分相关的请求。

php artisan make:controller RatingController

app/Http/Controllers/RatingController.php 文件中定义控制器:

namespace AppHttpControllers;

use AppModelsRating;
use IlluminateHttpRequest;

class RatingController extends Controller
{
    public function store(Request $request)
    {
        $rating = Rating::create([
            'user_id' => $request->input('user_id'),
            'product_id' => $request->input('product_id'),
            'score' => $request->input('score')
        ]);

        return response()->json($rating, 201);
    }

    public function update(Request $request, $id)
    {
        $rating = Rating::find($id);

        if ($rating) {
            $rating->update([
                'score' => $request->input('score')
            ]);

            return response()->json($rating, 200);
        } else {
            return response()->json(['message' => 'Rating not found'], 404);
        }
    }

    public function destroy($id)
    {
        $rating = Rating::find($id);

        if ($rating) {
            $rating->delete();

            return response()->json(['message' => 'Rating deleted'], 200);
        } else {
            return response()->json(['message' => 'Rating not found'], 404);
        }
    }
}

4. 创建评分表路由

最后,我们需要在 routes/api.php 文件中定义路由。

use AppHttpControllersRatingController;

Route::post('/ratings', [RatingController::class, 'store']);
Route::put('/ratings/{id}', [RatingController::class, 'update']);
Route::delete('/ratings/{id}', [RatingController::class, 'destroy']);

示例代码

下面是一个完整的示例代码,展示了如何在 Laravel 和 Eloquent 中创建和操作评分系统。

1. 安装 Laravel 和 Eloquent

确保你已经安装了 Laravel 和 Eloquent。如果没有安装,可以参考官方文档进行安装。

2. 创建评分表模型和迁移

按照上述步骤创建评分表模型和迁移。

3. 创建评分表控制器

按照上述步骤创建评分表控制器。

4. 创建评分表路由

按照上述步骤创建评分表路由。

通过以上步骤,你可以轻松地在 Laravel 和 Eloquent 中创建和操作评分系统。

黑板Bug讲师

黑板Bug讲师

介绍

本教程展示如何在Laravel应用程序中构建一个具有弹性的评分系统,使用Eloquent ORM。评分系统对于许多Web应用来说是不可或缺的功能,用于收集用户反馈。Laravel是一款流行且优雅的PHP Web应用程序框架,与Eloquent ORM相结合,使得实现这样的系统非常简单。

定义评级模型

首先,创建一个评分模型和迁移文件。运行 Artisan 命令:

php artisan make:model Rating -m

在创建的迁移文件中添加必要的列:

Schema::create('ratings', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id');
    $table->foreignId('post_id');
    $table->tinyInteger('rating');
    $table->timestamps();
});

迁移运行:

php artisan migrate

建立关系

对于这个例子,假设我们有一个名为“Post”的模型,在该模型中用户可以留下评价。在Rating模型中添加关系:

public function post()
{
    return $this->belongsTo(Post::class);
}

此外,还需要在Post模型中添加逆关系:

public function ratings()
{
    return $this->hasMany(Rating::class);
}

创建一个评分控制器

使用Artisan创建一个新的控制器:

php artisan make:controller RatingController

添加商店和更新方法:

public function store(Request $request)
{
    // Validation and storage logic
}

public function update(Rating $rating, Request $request)
{
    // Update logic
}

刀模板和形式

设计一个Blade模板中的评分组件:

<form method="POST" action="{{ route('ratings.store') }}">
    @csrf
    <div>
        // Rating input elements
    </div>
    <button type="submit">Submit Rating</button>
</form>

创建使用PUT方法的类似更新表单:

<form method="POST" action="{{ route('ratings.update', $rating) }}">
    @csrf
    @method('PUT')
    // Rating input elements for updating
</form>

在控制器中处理评分逻辑

在商店方法中,验证并保存评分:

$request->validate(['rating' => 'required|integer|between:1,5']);
$rating = new Rating($request->all());
// Attach user ID to the rating
$rating->user_id = auth()->id();
$rating->save();
return back()->with('message', 'Rating submitted successfully!');

在更新方法中,重用验证逻辑并更新:

$request->validate(['rating' => 'required|integer|between:1,5']);
$rating->update($request->all());
return back()->with('message', 'Rating updated successfully!');

计算聚合评分

为了计算Post模型的平均评分:

public function averageRating()
{
    return $this->ratings()->average('rating');
}

显示 Blade 模板中的平均率:

<p>Average Rating: {{ number_format($post->averageRating(), 1) }}</p>

闭幕词

虽然简单,本教程介绍了使用Laravel的Eloquent ORM建立基础评分系统的步骤。进一步的复杂性可能涉及AJAX以提供无缝用户体验、对多个提交进行验证以及更复杂的用户界面元素如星级评分。然而,有了这个基础,有许多机会可以根据任何特定应用程序的需求进行扩展和定制。

长工码奴1523

长工码奴1523

要构建一个基于 Laravel 和 Eloquent 的评分系统,首先需要确保已经安装了 Laravel 以及相关的依赖包(如 Eloquent)。以下是一些基本的步骤来创建这样一个系统:

  1. 创建数据库模型(Score.php):

    <?php
    
    namespace App;
    
    use IlluminateDatabaseEloquentModel;
    
    class Score extends Model
    {
       protected $fillable = ['user_id', 'product_id', 'rating'];
    
       public function user() {
           return $this->belongsTo('AppUser');
       }
    
       public function product() {
           return $this->belongsTo('AppProduct');
       }
    }
  2. 使用 Eloquent 完成评分数据的添加和更新操作:

    <?php
    
    namespace AppHttpControllers;
    
    use AppScore;
    use IlluminateHttpRequest;
    
    class ScoreController extends Controller
    {
       public function store(Request $request) {
           $score = new Score();
           $score->user_id = $request->input('user_id');
           $score->product_id = $request->input('product_id');
           $score->rating = $request->input('rating');
    
           $score->save();
    
           return redirect('/')->with('success', 'Your score has been saved.');
       }
    
       public function update(Request $request, $id) {
           $score = Score::find($id);
    
           if ($score) {
               $score->user_id = $request->input('user_id');
               $score->product_id = $request->input('product_id');
               $score->rating = $request->input('rating');
    
               $score->save();
    
               return redirect('/')->with('success', 'Your score has been updated.');
           } else {
               return redirect('/')->with('error', 'No score found with ID: ' . $id);
           }
       }
    }
  3. 添加路由:

    <?php
    
    Route::get('/', function () {
       return view('welcome');
    });
    
    Route::resource('scores', 'ScoreController');
  4. 在控制器中处理用户请求:

    <?php
    
    namespace AppHttpControllers;
    
    use AppScore;
    use IlluminateHttpRequest;
    
    class ScoreController extends Controller
    {
       public function __construct()
       {
           $this->middleware('auth');
       }
    
       public function show($id)
       {
           $score = Score::findOrFail($id);
           return view('show', compact('score'));
       }
    }
  5. 部署到生产环境:

    • 将项目打包为 Laravel 应用程序。
    • 启动并访问应用程序。

以上就是在 Laravel + Eloquent 中构建评分系统的示例。通过这些步骤,你可以创建一个可以接受用户输入并保存评分的数据管理系统。