多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] 多态:是指并不明确指向和谁关联,也就是说可以和任何库进行关联 示例表结构 文章有评论,视频也有评论,共用评论表 comments 评论表 | 键名 | 类型 | | --- | --- | | id | PK | | title | varchar(200) | | table_type | varchar(200) | | table_id | integer | | created_at | timestamp | | updated_at | timestamp | # 实现 Post.php ~~~ public function comments() { return $this->morphMany(Comment::class, 'table'); } ~~~ Video.php ``` public function comments() { return $this->morphMany(Comment::class,'table'); } ``` Comment.php ``` public function commentable() { return $this->morphTo('table'); } ``` Comment表中一些数据 ``` table_id就是对应Video或者Post表中的id table_type就是对应他们的命名空间,比如App\Models\Post ``` > 字段中的 table_type、table_id 的前缀table,对应 morphMany、morphTo 中的参数 > $this->morphMany > 加到任意Model,那个Model就具备了评论的功能,很方便 # 操作 ## 查 Post查评论 ``` $post=Post::find(1); $post->comments->toArray(); ``` Comment查对应的关联 ``` $comment=Comment::find(2); $comment->commentable; ``` ## 新增 比如,为第二条文章新增一条数据 ``` Post::find(2)->comments()->create(['title'=>'new data']); ``` ## 补充 在 AppServiceProvider boot 方法中自定义多态关联的类型字段。\ 这个可以按照项目需求来写 ~~~ use App\Models\Post; use App\Models\Video; use Illuminate\Database\Eloquent\Relations\Relation; public function boot() { $this->bootEloquentMorphs(); } /** * 自定义多态关联的类型字段 */ private function bootEloquentMorphs() { Relation::morphMap([ Post::TABLE => Post::class, Video::TABLE => Video::class, ]); } ~~~ 参考[1对多](https://www.kancloud.cn/jdxia/laravel5note/388604)