Friday, February 19, 2016

Laravel 5.2 : Many To Many Polymorphic Relations

Hi, Today we will discuss about many to many polymorphic relations in laravel 5.2.

Table Structure

In addition to traditional polymorphic relations, we may also define "many-to-many" polymorphic relations. For example, a blog Post and Video model could share a polymorphic relation to a Tag model. Using a many-to-many polymorphic relation allows us to have a single list of unique tags that are shared across blog posts and videos. First, let's examine the table structure:

posts
    id - integer
    name - string

videos
    id - integer
    name - string

tags
    id - integer
    name - string

taggables
    tag_id - integer
    taggable_id - integer (post_id or video_id)
    taggable_type - string (type should be App\Post and App\Video)

Model Structure

Next, we're ready to define the relationships on the model. The Post and Video models will both have a tags method that calls the morphToMany method on the base Eloquent class:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}

class Video extends Model
{
    /**
     * Get all of the tags for the post.
     */
    public function tags()
    {
        return $this->morphToMany('App\Tag', 'taggable');
    }
}

Defining The Inverse Of The Relationship

Next, on the Tag model, we should define a method for each of its related models. So, for this example, we will define a posts method and a videos method:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    /**
     * Get all of the posts that are assigned this tag.
     */
    public function posts()
    {
        return $this->morphedByMany('App\Post', 'taggable');
    }

    /**
     * Get all of the videos that are assigned this tag.
     */
    public function videos()
    {
        return $this->morphedByMany('App\Video', 'taggable');
    }
}

Retrieving The Relationship

Once our database table and models are defined, we may access the relationships via our models. For example, to access all of the tags for a post, we can simply use the tags dynamic property:

Open the terminal and run the below command

php artisan tinker

then $post = App\Post::find(1)->tags;

$video = App\Video::find(1)->tags;

We may also retrieve the owner of a polymorphic relation from the polymorphic model by accessing the name of the method that performs the call to morphedByMany. In our case, that is the posts or videos methods on the Tag model. So, we will access those methods as dynamic properties:

$tag = App\Tag::find(1)->video;


Thanks.

No comments:

Post a Comment