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. python gevent mokey

    #eg: monkey的理解 import gevent import socket urls = ['www.baidu.com', 'www.gevent.org', 'www.python.or ...

  2. 总是Eqw

    1.投递总是Eqw状态 qstat -j job_ID #Eqw状态的job id qconf -sq all.q |grep host qconf -shgrp @allhosts

  3. Json Web Token JJWT

    什么是JWT? Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站 ...

  4. 大数据入门到精通2--spark rdd 获得数据的三种方法

    通过hdfs或者spark用户登录操作系统,执行spark-shell spark-shell 也可以带参数,这样就覆盖了默认得参数 spark-shell --master yarn --num-e ...

  5. java方法中增加不固定参数

    JDK1.5以上支持 一.定义方法 有时方法的参数个数不固定,可以使用...来省略个数,使用时直接遍历即可,例如下面的方法 public class hi { public void print(St ...

  6. 六:python 对象类型详解二:字符串(下)

    一:字符串方法: 方法就是与特定对象相关联在一起的函数.从技术的角度来讲,它们是附属于对象的属性,而这些属性不过是些可调用的函数罢了.Python 首先读取对象方法,然后调用它,传递参数.如果一个方法 ...

  7. 第十章 优先级队列 (a1)需求与动机

  8. verilog之inout

    1.inout 类型的data信号 写操作有效时(rd_wr_l=0):data端口输入信号,此时data为高阻态,允许对其进行赋值. 读操作有效时(rd_wr_l=1):data端口输出信号,此时d ...

  9. PHP文件上传与下载

    一:上传文件与报错 $_FILES 超全局数组,包含了有关上传文件的所有信息! 而且,这个数组中只包含文件相关信息,其他数据依然在$_POST里面$_FILES是一个二维数组,每上传一个文件,都是数组 ...

  10. Oracle触发器用法实例详解

    转自:https://www.jb51.net/article/80804.htm. 本文实例讲述了Oracle触发器用法.分享给大家供大家参考,具体如下: 一.触发器简介 触发器的定义就是说某个条件 ...