多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1.配置路由 ~~~ Route::get('api/:version/category/all','api/:version.Category/getAllCategories'); ~~~ 2.新建Category.php模型 ~~~ <?php namespace app\api\model; class Category extends BaseModel { public function products() { return $this->hasMany('Product', 'category_id', 'id'); } public function img() { return $this->belongsTo('Image', 'topic_img_id', 'id'); } public static function getCategories($ids) { $categories = self::with('products') ->with('products.img') ->select($ids); return $categories; } public static function getCategory($id) { $category = self::with('products') ->with('products.img') ->find($id); return $category; } } ~~~ 3.新建异常类CategoryException.php ~~~ <?php namespace app\lib\exception; class CategoryException extends BaseException { public $code = 404; public $msg = '指定类目不存在,请检查商品ID'; public $errorCode = 20000; } ~~~ 4.新建控制器类Category .php ~~~ <?php namespace app\api\controller\v1; use app\api\model\Category as CategoryModel; use app\lib\exception\CategoryException; use think\Controller; class Category extends Controller { //获取全部类目列表,但不包含类目下的商品 public function getAllCategories() { $categories = CategoryModel::all([], 'img'); if(empty($categories)){ /*throw new MissException([ 'msg' => '还没有任何类目', 'errorCode' => 50000 ]);*/ throw new CategoryException(); } return $categories; } } ~~~ 结果 ![](https://box.kancloud.cn/8a769698ef935dd3c64c89d94bf2900d_945x722.png)