laravel-api(dingo) Include 机制
2018年11月13日lnclude机制的主要作用就是, 获取这个数据的,关于的额外数据。
1.编辑变形金刚文件
打开app\Transformers\TopicTransformer.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?php namespace App\Transformers; use App\Models\Topic; #引入文章模型 use League\Fractal\TransformerAbstract; #引入数据转换类 class TopicTransformer extends TransformerAbstract { protected $availableIncludes = ['user', 'category']; /** * 数据转化类 * @param Topic $topic * @return array */ public function transform(Topic $topic) { return [ 'id' => $topic->id, 'title' => $topic->title, 'body' => $topic->body, 'user_id' => (int)$topic->user_id, 'category_id' => (int)$topic->category_id, 'reply_count' => (int)$topic->reply_count, 'view_count' => (int)$topic->view_count, 'last_reply_user_id' => (int)$topic->last_reply_user_id, 'excerpt' => $topic->excerpt, 'slug' => $topic->slug, 'created_at' => $topic->created_at->toDateTimeString(), 'updated_at' => $topic->updated_at->toDateTimeString(), ]; } /** * 引入用户信息,首先模型当中要有这个user方法 * @param Topic $topic * @return mixed */ public function includeUser(Topic $topic) { return $this->item($topic->user, new UserTransformer()); } /** * 引入分类信息,首先模型中要有这个category方法 * @param Topic $topic * @return mixed */ public function includeCategory(Topic $topic) { return $this->item($topic->category, new CategoryTransformer()); } } |
2.开始测试数据
1 2 3 |
{{host}}/api/topics?include=user,category {{host}}/api/topics?include=category {{host}}/api/topics?include=user |