Yii2 RESTful API 学习笔记第二节:基础接口增强

一、列表接口只返回需要的字段数据:

方法一:请求地址中添加所需字段:

//读取列表数据(只返回需要的字段)
bindReadTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles?fields=id,title,content',
  })
},

方法二:重写AR::fields()方法:

public function fields()
{
    //return parent::fields();
    return [
        'id',
        'title',
        'content',
        'status' => function($model){
            return self::$statusList[$model->status];
        },
        'cid' => function($model){
            return $model->category->title;  // 显示关联模型的信息
        },
    ];
}

二、返回资源的操作(更新、删除)链接:

namespace api\models;

use yii\db\ActiveRecord;
use yii\helpers\Url;
use yii\web\Link;
use yii\web\Linkable;

class Article extends ActiveRecord implements Linkable
{
    public function getLinks()
    {
        return [
            Link::REL_SELF => Url::to(['article/view', 'id' => $this->id], true),
            'update' => Url::to(['article/update', 'id' => $this->id], true),
            'delete' => Url::to(['article/delete', 'id' => $this->id], true),
            'index' => Url::to(['articles'], true),
        ];
    }
}

三、自定义分页:

请求时添加page参数,控制显示第几页:

<?php
namespace api\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\ActiveController;

class ArticleController extends ActiveController
{
    public $modelClass = 'api\models\Article';

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index']);
        return $actions;
    }

    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => $this->modelClass::find(),
            'pagination' => [
                'pageSize' => 5,  // 每页显示多少行
            ],
        ]);
    }
}

四:搜索功能示例:

1. 小程序相关代码:

//wxml:
<view bindtap='bindSearchTap'>文章搜索</view>

//js:
//文章搜搜
bindSearchTap: function () {
  wx.request({
    url: 'http://tongmengcms2.ccc/api/articles/search',
    header: {
      'Content-Type': 'application/json'
    },
    method: 'POST',
    data: {
      keyword: "添加"
    },
    success: function (res) {
      console.log(res.data)
    }
  })
},

2. 控制器代码:

public function actionSearch()
{
    return $this->modelClass::find()->where(['like', 'title', Yii::$app->request->post('keyword')])->all();
}
3. 配置文件:
'urlManager' => [
    'enablePrettyUrl' => true,  // 路由友好化
    'enableStrictParsing' => true,  // 启用严格解析
    'showScriptName' => false,  // 是否显示单入口
    'rules' => [                // 路由规则
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => 'article',
            'extraPatterns' => [  // 新增操作列表
                'POST search' => 'search',
            ],
        ],
    ],
],