多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1.添加路由 ~~~ Route::get('api/:version/product/by_category','api/:version.Product/getAllInCategory'); ~~~ 2.修改database.php数据集返回类型的配置 ~~~ // 数据集返回类型 // 'resultset_type' => 'array', 'resultset_type' => 'collection', ~~~ 3.修改Product.php模型 ~~~ <?php namespace app\api\model; class Product extends BaseModel { protected $autoWriteTimestamp = 'datetime'; 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); } public static function getMostRecent($count) { $products = self::limit($count) ->order('create_time desc') ->select(); return $products; } //获取某分类下商品 public static function getProductsByCategoryID($categoryID) { $products=self::where('category_id','=',$categoryID)->select(); return $products; } } ~~~ 4.修改Product.php控制器 ~~~ <?php namespace app\api\controller\v1; use app\api\model\Product as ProductModel; use app\api\validate\Count; use app\api\validate\IDMustBePostiveInt; use app\lib\exception\ProductException; use think\Controller; class Product extends Controller { //获取指定数量的最近商品 public function getRecent($count = 15) { (new Count())->goCheck(); $products = ProductModel::getMostRecent($count); if ($products->isEmpty()){ throw new ProductException(); } //隐藏summary的方法 $products=$products->hidden(['summary']); return $products; } //获取某分类下全部商品 public function getAllInCategory($id) { (new IDMustBePostiveInt())->goCheck(); $products = ProductModel::getProductsByCategoryID($id); if ($products->isEmpty()) { throw new ProductException(); } //隐藏summary的方法 $products=$products->hidden(['summary']); return $products; } } ~~~ 结果: ![](https://box.kancloud.cn/63a93c8d3071848ba940afe8f87091ae_1079x649.png)