Laravel Many to Many Polymorphic Relationship
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的更多相关文章
- Laravel Vuejs 实战:开发知乎 (9)定义话题与问题关系
1.话题[Topic] 执行命令: php artisan make:model Topic –cmr 修改****_**_**_create_topics_table.php数据库迁移文件如下: c ...
- laravel model relationship
laravel支持多种模型之间的relation,对应着模型间的one2one, one2many,many2many,hasManyThrough,Polymorphic, many2many po ...
- Laravel Relationship Events
Laravel Relationship Events is a package by Viacheslav Ostrovskiy that adds extra model relationship ...
- Laravel Eloquent ORM
Eloquent ORM 简介 基本用法 集体赋值 插入.更新.删除 软删除 时间戳 查询范围 关系 查询关系 预先加载 插入相关模型 触发父模型时间戳 与数据透视表工作 集合 访问器和调整器 日期调 ...
- PHP and laravel知识点小小积累
function () use ($x, &$y){} 自从PHP5.3开始有了closure/匿名函数的概念,在这里的use关键词的作用是允许匿名函数capture到父函数scope 内存在 ...
- Laravel五大功能之Eloquent关系模式
Eloquent是Laravel的原始ActiveRecord是实现的,建立在Laravel的Fluent Query Builder之上的,所以Eloquent类和Fluent类是一样的,能实现复杂 ...
- Laravel教程 八:queryScope 和 setAttribute
Laravel教程 八:queryScope 和 setAttribute 此文章为原创文章,未经同意,禁止转载. Laravel Eloquent Database 直接就是按照上一节所说的那样,我 ...
- laravel速记(笔记)
命令行: php artisan controller:make UserController This will generate the controller at /app/controller ...
- laravel Authentication and Security
Creating the user modelFirst of all, we need to define the model that is going to be used to represe ...
随机推荐
- Transparency Sort Mode
[Transparency Sort Mode] Transparency Sort Mode, which allows you to control how Sprites are sorted ...
- ubuntu下搭建node server的几个坑
[ubuntu下搭建node server的几个坑] 1.环境变量 process.env.PORT需要使用 export PORT=80设置 windows下是set PORT=80 2.命令连结 ...
- excel 数据量较大边查询边输入到excel表格中
public Resultmodel getexpenseMessagx(HttpServletResponse response, String date1, String date2) { lon ...
- linux系统修改系统时间与时区
有装过Linux系统的人,可能都会有这样的经历,就是该机器安装windows系统时,时间正确,但是安装了linux系统后,尽管时区选择正确,也会发现系统时间不对.这是由于安装系统时采用了UTC,那么什 ...
- python 文件操作: 文件操作的函数, 模式及常用操作.
1.文件操作的函数: open("文件名(路径)", mode = '模式', encoding = "字符集") 2.模式: r , w , a , r+ , ...
- angularjs $injector:nomod
参考 http://blog.163.com/gis_warrior/blog/static/19361717320153111134135/ 检查是否有[],或者是否多次定义同一个module 标准 ...
- tomcat指向外部项目
参考 https://www.cnblogs.com/ysocean/p/6893446.html conf/server.xml中增加 <Context path="/myweb&q ...
- background和background-color的区别
在设置输入框变成一条线的样式时遇到一个小问题. 无论怎么设置 输入框的背景都没有变 而设置background: #aaa;背景就改变了. 后来发现原因 background 可以设置 背景颜色.背景 ...
- 二:python 对象类型概述
1,为什么使用内置类型: a)内置对象使程序更容易编写 b)内置对象是扩展的组件 c)内置对象往往比定制的数据结构更加高效 d)内置对象是语言的标准的一部分 2,python 的主要内置对象 对象类 ...
- Linux下常用的编辑文件与保存命令
打开文件: vi aaa.conf 编辑: i 编辑结束,按ESC 键 跳到命令模式,然后输入退出命令: :w (write)保存文件但不退出vi 编辑 :w! 强制保存,不退出vi 编辑 :w fi ...