Debarshi Das
Debarshi Das

Reputation: 49

Laravel multiple relation in a same table

In my project, users can like & comment on feeds & forums. So, there is a contribution page where the user can see where he has provided his input (like or comment) sorted by created_at time.

There may be another feature in future like feed & forum where user can also provide like & comment.

In my contribution page, I want to list data like this -

But I am stuck in database design. So far I am trying this -

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();
});

But it will cause a query loop when I retrieve the data. So, is there any better approach to what I am trying to get?

Upvotes: 0

Views: 1128

Answers (1)

Repox
Repox

Reputation: 15476

You are probably looking for Polymorphic Relationships.

That enables you to simplify the relationship by providing an ID of the related model and a naming of the related model instead.

A sample migration would look like this, using the morph method as inspiration (since you're using UUID's):

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

This should enable you to do something like:

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');
    }
}

You should be able to retrieve the users contributions that way and defining the action based on the morphed instance type.

Upvotes: 2

Related Questions