同一个表中的 Laravel 多重关系

时间:2021-06-04 05:20:11

标签: laravel eloquent

在我的项目中,用户可以对提要和论坛点赞和评论。因此,有一个贡献页面,用户可以在其中查看他提供的输入(赞或评论)的位置,按 created_at 时间排序。

将来可能会有另一个功能,例如供稿和论坛,用户还可以在其中提供喜欢和评论。

在我的投稿页面,我想列出这样的数据 -

  • 您在 user_2 - feed_title 的 Feed created_at 发表了评论>comment
  • 您在 user_2
  • 点赞了 feed_title 的 Feed created_at
  • 您在 user_3forum_title 论坛 created_at 上发表了评论 - >comment
  • 您在user_3
  • 点赞了forum_title的论坛created_at

但我被困在 database 设计中。到目前为止,我正在尝试这个 -

Schema::create('contributions', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id');
            $table->uuid('contribution_id'); // id of my like/comment
            $table->string('contribution_type'); // feed_like/feed_comment/forum_like/forum_comment
            $table->uuid('target_id'); // id of feed/forum where I provided comment or like
            $table->timestamps();
});

但是当我检索数据时它会导致查询循环。那么,有没有更好的方法来达到我想要的效果?

1 个答案:

答案 0 :(得分:2)

您可能正在寻找Polymorphic Relationships

这使您能够通过提供相关模型的 ID 和相关模型的命名来简化关系。

示例迁移如下所示,使用 morph 方法作为灵感(因为您使用的是 UUID):

Schema::create('contributions', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->uuid('user_id');
            $table->uuid('contributable_id');
            $table->string('contributable_type');
            $table->timestamps();
});

这应该使您能够执行以下操作:

class Contribution extends Model {

    public function contributable() {
        return $this->morphTo();
    }

}



class User extends Model
{
    /**
     * Get the user's contributions.
     */
    public function contributions()
    {
        return $this->morphToMany(Contribution::class, 'contributable');
    }
}

您应该能够以这种方式检索用户贡献并根据变形实例类型定义操作。