未加星标

Polymorphic relationship Laravel

字体大小 | |
[开发(php) 所属分类 开发(php) | 发布者 店小二03 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

This example will show a typical "Attachment" need. The Laravel docs really do cover alot as seen here especially "Polymorphic Relation Table Structure” . I cover many to many polymorphic relationshipshere

I will cover an example of an Attachment that has some fields. And it is related to a model, in this example "Post"

Using the Way Generators to make this resource.

php artisan generate:resource attachment --fields="attachable_type:string, attachable_id:integer, name:string, file_name:string, note:text, tag:string”

As noted in the laravel docs our table for Attachments would look something like this

post id - integer name - string body - text attachments id - integer file_name - string attachable_id - integer attachable_type - string

So we are making a table/model Attachment. The model will use the "attachable" syntax to dynamically reference another model and model id.

In the Post model I set that this relationship exists

#app/models/Post.php public function attachments() { return $this->morphTo("Attachment", "attachable"); }

The Attachment model file is this

<?php #app/models/Attachment.php class Attachment extends \Eloquent { protected $fillable = [ "attachable_type", "attachable_id", "name”, “file_name”, "note", "tag" ]; public function attachable() { return $this->morphTo(); } }

Finally if we where to seed the db or add content the table for Attachments would look like this


Polymorphic relationship Laravel

the attachable_type is the model class so if the namespace was Acme\Post then that would be "Acme\Post

That is it. As long as you include it in your results you will see it in your output.

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

主题: Laravel
分页:12
转载请注明
本文标题:Polymorphic relationship Laravel
本站链接:http://www.codesec.net/view/533565.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(php) | 评论(0) | 阅读(24)