Laravel 同一模型上的多个关系

问题描述 投票:0回答:1

我希望用户能够互相评分。我不确定要使用哪种关系以及如何正确执行。由于

one-to-many
是由一个用户给予另一个用户的,因此
rating
在这种情况下效果会最好吗?

这是我到目前为止所拥有的:

用户:

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

评分:

public function users(): BelongsTo
{
    return $this->belongsTo(User::class);
}

迁移:

public function up(): void
{
    Schema::create('ratings', function (Blueprint $table) {
        $table->id();

        $table->integer('rating');

        $table->foreignId('user_id');

        $table->timestamps();
    });
}

我不确定整个关系,因为评分既是由用户给出的,也是给用户的。我与给予和接收用户有何不同?

laravel
1个回答
0
投票

您可以在评级表上添加另一列,其中包含创建评级的用户的 ID。

$table->foreignId('user_id');      // user ID receiving the rating
$table->foreignId('created_by');   // user ID that created the rating

评分:

public function user(): BelongsTo
{
    return $this->belongsTo(User::class);
}

public function createdBy(): BelongsTo
{
    return $this->belongsTo(User::class, 'created_by');
}
© www.soinside.com 2019 - 2024. All rights reserved.