全栈微信小程序商城 学习笔记8.2 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_product表

theme_id	主题外键
product_id	商品外键

分析

一个theme下面有多个product,一个product也可能属于多个theme,所以是多对多关系,需要引入中间表theme_product进行关联
不需要建立中间表theme_product的模型,tp5已经自动处理

准备工作

application oute.php

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

注意要开启路由完整匹配模式,否则会被theme简要信息接口的路由匹配

applicationconfig.php

return [
    //...
    'route_complete_match'   => true,
    //...
];

Product模型

applicationapimodelProduct.php

<?php

namespace appapimodel;

class Product extends BaseModel
{
    //pivot 多对多关系tp5自动带上的中间表属性,这里不需要
    protected $hidden = [
        'delete_time', 'main_img_id', 'pivot', 'from', 'category_id', 'create_time', 'update_time'
    ];
    public function getMainImgUrlAttr($value, $data) {
        return $this->prefixImgUrl($value, $data);
    }
}

Theme模型

applicationapimodelTheme.php

<?php

namespace appapimodel;

class Theme extends BaseModel
{
    //...
    public function products()
    {
        // 多对多关系
        // 参数:1.关联模型名 2.中间表名 3.外键名 4.当前模型关联键名
        return $this->belongsToMany('Product', 'theme_product', 'product_id', 'theme_id');
    }
    public static function getThemeWithProducts($id)
    {
        $themes = self::with('products,topicImg,headImg')
            ->find($id);
        return $themes;
    }
}

Theme控制器

applicationapicontrollerv1Theme.php,省略部分代码

<?php


namespace appapicontrollerv1;


use appapivalidateIDCollection;
use appapimodelTheme as ThemeModel;
use appapivalidateIDMustBePositiveInt;
use applibexceptionThemeException;

class Theme
{
    //...
    public function getComplexOne($id) {
        (new IDMustBePositiveInt())->goCheck();
        $theme = ThemeModel::getThemeWithProducts($id);
        if (!$theme) {
            throw new ThemeException();
        }
        return $theme;
    }
}

测试

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