Laravel中用户间评分的模型关联设计疑问
用户间互相评分的关联关系实现方案
你之前的思路只覆盖了单一方向的关联,因为评分涉及评分发起者和评分接收者两个用户,所以需要在ratings表中添加两个外键,分别关联到用户表,再通过模型的关联方法明确区分两者。
1. 调整迁移文件
首先修改ratings表的迁移,新增两个外键字段:
rater_id:存储发起评分的用户IDrated_id:存储接收评分的用户ID
示例迁移代码:
public function up() { Schema::create('ratings', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('rater_id'); // 评分者ID $table->unsignedBigInteger('rated_id'); // 被评分者ID $table->integer('score'); // 评分值,比如1-5分 $table->text('comment')->nullable(); // 可选评论文字 $table->timestamps(); // 外键约束 $table->foreign('rater_id')->references('id')->on('users')->onDelete('cascade'); $table->foreign('rated_id')->references('id')->on('users')->onDelete('cascade'); }); }
2. 设置模型关联
Rating模型
定义两个BelongsTo关联,分别指向评分发起者和接收者:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Rating extends Model { protected $fillable = ['rater_id', 'rated_id', 'score', 'comment']; // 关联评分发起者 public function rater(): BelongsTo { return $this->belongsTo(User::class, 'rater_id'); } // 关联评分接收者 public function ratedUser(): BelongsTo { return $this->belongsTo(User::class, 'rated_id'); } }
User模型
定义两个HasMany关联,分别对应用户给出的评分和收到的评分:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class User extends Model { // ... 其他原有代码 // 获取该用户给出的所有评分 public function givenRatings(): HasMany { return $this->hasMany(Rating::class, 'rater_id'); } // 获取该用户收到的所有评分 public function receivedRatings(): HasMany { return $this->hasMany(Rating::class, 'rated_id'); } }
3. 使用示例
- 获取某个用户收到的所有评分及评分者信息:
$user = User::find(1); $receivedRatings = $user->receivedRatings()->with('rater')->get();
- 创建一条新评分(用户1给用户2打5分):
Rating::create([ 'rater_id' => 1, 'rated_id' => 2, 'score' => 5, 'comment' => '非常靠谱的合作伙伴' ]);
这种设计清晰区分了评分的双向关系,也能通过Eloquent关联轻松查询相关数据,比单一的one-to-many更适配用户互相评分的场景。
内容的提问来源于stack exchange,提问作者M A
相关产品推荐
相关产品推荐

