在我的项目中,用户可以对提要和论坛点赞和评论。因此,有一个贡献页面,用户可以在其中查看他提供的输入(赞或评论)的位置,按 created_at
时间排序。
将来可能会有另一个功能,例如供稿和论坛,用户还可以在其中提供喜欢和评论。
在我的投稿页面,我想列出这样的数据 -
user_2
- 对 feed_title
的 Feed created_at
发表了评论>comment
user_2
feed_title
的 Feed created_at
user_3
的 forum_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();
});
但是当我检索数据时它会导致查询循环。那么,有没有更好的方法来达到我想要的效果?
答案 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');
}
}
您应该能够以这种方式检索用户贡献并根据变形实例类型定义操作。