全栈微信小程序商城 学习笔记8.4 category分类接口编写

相关表字段一览

category表

id	
name	分类名称
topic_img_id	外键,关联image表
delete_time	
description	描述
update_time	

准备工作

application oute.php

Route::get('api/:version/category/all', 'api/:version.Category/getAllCategories');

异常处理

applicationlibexceptionCategoryException.php

<?php

namespace applibexception;


class CategoryException extends BaseException
{
    public $code = 404;
    public $msg = '指定类目不存在,请检查商品ID';
    public $errorCode = 20000;
}

Category模型

applicationapimodelCategory.php

class Category extends BaseModel
{
    public function img()
    {
        return $this->belongsTo('Image', 'topic_img_id', 'id');
    }
}

Category控制器

applicationapicontrollerv1Category.php

class Category
{
    public function getAllCategories()
    {
        $categories = CategoryModel::all([], 'img'); 
        if($categories -> isEmpty()){
           throw new CategoryException();
        }
        return $categories;
    }
}

测试

原文地址:https://www.cnblogs.com/Qyhg/p/14764777.html