Laravel5.1 框架模型多态关联用法实例分析
网络编程 2021-07-04 23:05www.168986.cn编程入门
这篇文章主要介绍了Laravel5.1 框架模型多态关联用法,结合实例形式分析了laravel5.1框架模型多态关联具体实现、使用方法与操作注意事项,需要的朋友可以参考下
本文实例讲述了Laravel5.1 框架模型多态关联用法。分享给大家供大家参考,具体如下:
什么是多态关联? 一个例子你就明白了:好比如说评论 它可以属于视频类 也可以属于文章类,当有个需求是 从评论表中取到视频类的数据,这就需要用到多态关联了。
简单的一句话总结:一张表对应两张表。
1 实现多态关联
1.1 文章表的结构
public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body');$table->timestamps(); }); }
1.2 视频表结构
public function up() { Schema::create('videos', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); }
1.3 评论表结构
public function up() { Schema::create('ments', function (Blueprint $table) { $table->increments('id'); $table->text('content'); $table->integer('item_id'); $table->string('item_type'); $table->timestamps(); }); }
↑ 这里需要指定 item_id 和 item_type 单一介绍一下 item_type 它主要是区别关联于那张表的 我们这里它只有两个值:App\Article 或 App\Video。
1.4 编写多态关联
Article 和 Video:
public function ments() { /** * 第二个参数:如果你的前缀是item_ 那么就写item 如果是别的就写别的。 * 第三个参数:item_type * 第四个参数:item_id * 第五个参数:关联到那个表的键 * (以上除了第二个参数都可以省略) */ return $this->morphMany(Comment::class, 'item', 'item_type', 'item_id', 'id'); }
Comment:
public function video() { /** * 三个参数都可以省略 不过K建议你还是写全 */ return $this->morphTo('item', 'item_type', 'item_id'); }
使用:
Route::get('/', function () { $video = App\Video::find(8); foreach ($video->ments as $ment) { echo $ment->id . ": " . $ment->item_type; } });
更多关于Laravel相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》及《》
希望本文所述对大家基于Laravel框架的PHP程序设计有所帮助。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程