Many to many Polymorphic relationship is also a little bit complicated to understand. For example, if you have posts, videos, and tag tables, you require to connect with each other with your requirement like every post have multiple tags and same for videos too. Also every tag many are connected with multiple post or multiple videos too. But we can easily do it using just one table "taggables". Just read the article and you got it.

In this article, you can understand how to create polymorphic many-to-many relationships with migration with a foreign key schema for one to many relationships, use sync with a pivot table, create records, attach records, get all records, delete, update, where condition and everything related to many to many polymorphic relationship.

In this example, i will create "posts", "videos", "tags" and "taggables" tables. each table is connected with each other. now we will create many to many polymorphic relationships with each other by using laravel Eloquent Model. We will first create database migration, then model, retrieve records and then how to create records too. So you can also see database table structure on below screen.

Polymorphic Many to Many Relationship will use "morphToMany()" and "morphedByMany()" for relation.

Create Migrations:

Now we have to create migration of "posts", "videos", "tags" and "taggables" table. so let's create like as below:

posts table migration:

Schema::create('posts', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

videos table migration:

Schema::create('videos', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

tags table migration:

Schema::create('tags', function (Blueprint $table) {

$table->increments('id');

$table->string("name");

$table->timestamps();

});

taggables table migration:

Schema::create('taggables', function (Blueprint $table) {

$table->integer("tag_id");

$table->integer("taggable_id");

$table->string("taggable_type");

});

Create Models:

Here, we will create Post, Video and Tag table model. we will also use "morphToMany()" and "morphedByMany()" for relationship of both model.

Post Model:

<?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(Tag::class, 'taggable');

}

}

Video Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Video extends Model

{

/**

* Get all of the tags for the post.

*/

public function tags()

{

return $this->morphToMany(Tag::class, 'taggable');

}

}

Tag Model:

<?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(Post::class, 'taggable');

}

/**

* Get all of the videos that are assigned this tag.

*/

public function videos()

{

return $this->morphedByMany(Video::class, 'taggable');

}

}

Retrieve Records:

$post = Post::find(1);

dd($post->tags);

$video = Video::find(1);

dd($video->tags);

$tag = Tag::find(1);

dd($tag->posts);

$tag = Tag::find(1);

dd($tag->videos);

Create Records:

$post = Post::find(1);

$tag = new Tag;

$tag->name = "ItSolutionStuff.com";

$post->tags()->save($tag);

$video = Video::find(1);

$tag = new Tag;

$tag->name = "ItSolutionStuff.com";

$video->tags()->save($tag);

$post = Post::find(1);

$tag1 = new Tag;

$tag1->name = "ItSolutionStuff.com";

$tag2 = new Tag;

$tag2->name = "ItSolutionStuff.com 2";

$post->tags()->saveMany([$tag1, $tag2]);

$video = Video::find(1);

$tag1 = new Tag;

$tag1->name = "ItSolutionStuff.com";

$tag2 = new Tag;

$tag2->name = "ItSolutionStuff.com 2";

$video->tags()->saveMany([$tag1, $tag2]);

$post = Post::find(1);

$tag1 = Tag::find(3);

$tag2 = Tag::find(4);

$post->tags()->attach([$tag1->id, $tag2->id]);

$video = Video::find(1);

$tag1 = Tag::find(3);

$tag2 = Tag::find(4);

$video->tags()->attach([$tag1->id, $tag2->id]);

$post = Post::find(1);

$tag1 = Tag::find(3);

$tag2 = Tag::find(4);

$post->tags()->sync([$tag1->id, $tag2->id]);

$video = Video::find(1);

$tag1 = Tag::find(3);

$tag2 = Tag::find(4);

$video->tags()->sync([$tag1->id, $tag2->id]);

I hope you understand of many to many relationship...

Laravel Many to Many Polymorphic Relationship的更多相关文章

  1. Laravel Vuejs 实战:开发知乎 (9)定义话题与问题关系

    1.话题[Topic] 执行命令: php artisan make:model Topic –cmr 修改****_**_**_create_topics_table.php数据库迁移文件如下: c ...

  2. laravel model relationship

    laravel支持多种模型之间的relation,对应着模型间的one2one, one2many,many2many,hasManyThrough,Polymorphic, many2many po ...

  3. Laravel Relationship Events

    Laravel Relationship Events is a package by Viacheslav Ostrovskiy that adds extra model relationship ...

  4. Laravel Eloquent ORM

    Eloquent ORM 简介 基本用法 集体赋值 插入.更新.删除 软删除 时间戳 查询范围 关系 查询关系 预先加载 插入相关模型 触发父模型时间戳 与数据透视表工作 集合 访问器和调整器 日期调 ...

  5. PHP and laravel知识点小小积累

    function () use ($x, &$y){} 自从PHP5.3开始有了closure/匿名函数的概念,在这里的use关键词的作用是允许匿名函数capture到父函数scope 内存在 ...

  6. Laravel五大功能之Eloquent关系模式

    Eloquent是Laravel的原始ActiveRecord是实现的,建立在Laravel的Fluent Query Builder之上的,所以Eloquent类和Fluent类是一样的,能实现复杂 ...

  7. Laravel教程 八:queryScope 和 setAttribute

    Laravel教程 八:queryScope 和 setAttribute 此文章为原创文章,未经同意,禁止转载. Laravel Eloquent Database 直接就是按照上一节所说的那样,我 ...

  8. laravel速记(笔记)

    命令行: php artisan controller:make UserController This will generate the controller at /app/controller ...

  9. laravel Authentication and Security

    Creating the user modelFirst of all, we need to define the model that is going to be used to represe ...

随机推荐

  1. select字符串

    [select字符串] select通常用于选择某中的某一列.如有表Download: 通常用select选择某一列,如: 当select一个字符串时,则会返回如下值: 结论:select中传递一个字 ...

  2. python 之面向对象

    继承粗体文本 标签(空格分隔): 继承 什么是继承: 继承是指类与类之间的关系,是一种什么"是"什么的关系,继承的功能之一就是用来解决代买重用问题,继承是一种创建新类的方式,在py ...

  3. sqlserver 查看当前连接数

    参考 https://www.cnblogs.com/lumnm/archive/2009/08/29/1556349.html SELECT * FROM[Master].[dbo].[SYSPRO ...

  4. poi excel 加粗

    参考 https://blog.csdn.net/wellto/article/details/52293202 XSSFWorkbook xwb = new XSSFWorkbook(); ... ...

  5. 数据库类型空间效率探索(三)-char

    测试环境 表信息 表数据量22.23万,占用空间44.494M 用到的sql语句 增加列:alter table t_type add column new_column char(1) defaul ...

  6. PHP 用正则获取URL的根域名

    function GetUrlRoot($url){ preg_match('/[\w][\w-]*\.(?:com\.cn|com|cn|co|net|org|gov|cc|biz|info)(\/ ...

  7. centos 7.2 安装域名服务器(bind9.9 集群--主从架构),私有域名服务器+缓存

    1.安装组件 yum install bind bind-utils -y 2.启动域名服务 service named start chkconfig named on ss -unlt |grep ...

  8. 顺时针打印矩阵(python)

    题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数 ...

  9. Maximum Gap (ARRAY - SORT)

    QUESTION Given an unsorted array, find the maximum difference between the successive elements in its ...

  10. synchronized细节问题(一)

    synchronized锁重入: 关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到一个对象的锁后,再次请求此对象时是可以再次得到该对象的锁. 下面 ...