全栈微信小程序商城 学习笔记8.1 theme简要信息接口编写

创建获取专题(theme)的简要信息的接口

专题相关表字段一览

theme表

id	
name	专题名称
description	专题描述
topic_img_id	主题图,外键
delete_time	
head_img_id	专题列表页,头图
update_time	

product表

id	
name	商品名称
price	价格,单位:分
stock	库存量
delete_time	
category_id	
main_img_url	主图ID号,这是一个反范式设计,有一定的冗余
from	图片来自 1 本地 ,2公网
create_time	创建时间
update_time	
summary	摘要
img_id	图片外键

image表

id	
url	图片路径
from	1 来自本地,2 来自公网
delete_time	
update_time

专题简要信息接口模型分析

Theme的topic_img和head_img,分别对应一个Image,一个Image也只能是一个Theme的topic_img或head_img,所以是一对一关系

准备工作

application oute.php

Route::get('api/:version/theme', 'api/:version.Theme/getSimpleList')

异常处理

applicationlibexceptionThemeException.php

<?php

namespace applibexception;

class ThemeException extends BaseException
{
    public $code = 404;
    public $msg = '指定主题不存在,请检查主题ID';
    public $errorCode = 30000;
}

接口验证

applicationapivalidateIDCollection.php

<?php
namespace appapivalidate;


class IDCollection extends BaseValidate
{
    // 千万不要在require|checkIDS中加空格
    // 不然你会哭的
    // 源码中是没有去处多余空格的判断的
    // 这将导致验证不执行
    protected $rule = [
        'ids' => 'require|checkIDs'
    ];

    protected $message = [
        'ids' => 'ids参数必须为以逗号分隔的多个正整数,仔细看文档啊'
    ];

    protected function checkIDs($value)
    {
        $values = explode(',', $value);
        if (empty($values)) {
            return false;
        }
        foreach ($values as $id) {
            if (!$this->isPositiveInteger($id)) {
                // 必须是正整数
                return false;
            }
        }
        return true;
    }
}

Theme模型

applicationapimodelTheme.php

class Theme extends BaseModel
{
    protected $hidden = ['delete_time', 'topic_img_id', 'head_img_id'];
    public function topicImg()
    {
        // 一对一关系
        // 注意主从关系,Theme有关联Image的外键,而Image中并没有此类字段,如果用Image关联Theme则要用hasOne
        return $this->belongsTo('Image', 'topic_img_id', 'id');
    }

    public function headImg()
    {
        return $this->belongsTo('Image', 'head_img_id', 'id');
    }
}

Theme控制器

class Theme
{
    public function getSimpleList($ids='') {
        $validate = new IDCollection();
        $validate->goCheck();
        $ids = explode(',', $ids);
        $result = ThemeModel::with('topicImg,headImg')->select($ids); 
        if ($result) {
            throw new ThemeException()
        }
        return $result
    }
}

测试

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