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 ...
随机推荐
- crontab -e文件存放路径
crontab -e结果存放在/var/spool/cron/crontabs中
- 大型运输行业实战_day11_1_aop理论与aop实际业务操作
1.aop概述 Spring的AOP:什么叫做AOP:Aspect oritention programming(面向切面编程)什么是切面:看图,业务方法 执行前后.AOP的目的:AOP能够将那些与业 ...
- html实现导航栏效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- VSC KeyNote
[VSC KeyNote] 1.前后跳转. Alt + LeftArrow, Alt + RightArrow 2.缩进问题. vsc默认缩进为4,但js代码里缩进依旧是2. 因为vscode默认启用 ...
- jQuery 设置/获取样式
参考 http://www.w3school.com.cn/jquery/jquery_css.asp $("#a").css("height"); $(&qu ...
- LocalDateTime TypeMismatch
@DateTimeFormat(pattern = "yyyy-MM-dd")@JsonFormat(pattern = "yyyy-MM-dd", timez ...
- SML + NL + HJ
Join是一种试图将两个表结合在一起的谓词,一次只能连接2个表,表连接也可以被称为表关联.在后面的叙述中,我们将会使用”row source”来代替”表”,因为使用row source更严谨一些,并且 ...
- SQLdeveloper同时显示多个表的窗口
- 忘记root密码,怎么办
当前账户拥有sudo权限,可以通过sudo passwd root来重置root密码.
- stm32 map文件的分析
相信有较大项目开发经验的朋友都曾遇到内存溢出的问题,那么大家都是如何分析这类问题的呢?大家遇到HardFault_Handler 有对map分析过吗? 首先讲述一下关于map在MDK-ARM中的配置. ...