【问题标题】:Custom action in Action with id in Rest ActiveController Yii2在 Rest ActiveController Yii2 中带有 ID 的操作中的自定义操作
【发布时间】:2016-12-22 22:21:56
【问题描述】:

尝试在 Rest API 中实现 GET 方法,以查询用户状态,例如获取用户/:id/状态

因此获取用户 ID #1 的状态将调用 /user/1/status

在配置中我有:

'urlManager'   => [
'enablePrettyUrl'     => true,
'enableStrictParsing' => true,
'showScriptName'      => false,
'rules'               => [
    [
        'class'      => 'yii\rest\UrlRule',
        'controller' => [
            'v1/user'
        ],
        'extraPatterns' => [
            'GET status' => 'status',
        ],
        'tokens'     => [
            '{id}' => '<id:\\w+>'
        ],
    ],
],

用户模型:

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;

class User extends ActiveRecord {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey() {
        return [ 'id' ];
    }

}

用户控制器:

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController {

    public $modelClass = 'api\modules\v1\models\User';

    public function actions() {
        $actions = parent::actions();

        unset(
            $actions[ 'index' ],
            $actions[ 'view' ],
            $actions[ 'create' ],
            $actions[ 'update' ],
            $actions[ 'delete' ],
            $actions[ 'options' ]
        );


        return $actions;
    }

    protected function verbs() {
        return [
            'status' => [ 'GET' ],
        ];
    }

    public function actionStatus( $id ) {

        return 1;
    }

}

但现在我不确定如何实际返回调用数据。

【问题讨论】:

  • 你的意思是我不确定如何实际返回数据
  • 我是否只是在 actionStatus 内部查询并返回 JSON?不确定 actionStatus 中应该发生什么

标签: yii2 yii2-api


【解决方案1】:
$user = User::findOne($id);
if ($user)
    return Json::encode(['success'=>true, 'data'=>$user->status]);
else
    return Json::encode(['success'=>false, 'message'=>"Can't find user"]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 2011-12-31
    • 2021-07-11
    • 2012-05-03
    相关资源
    最近更新 更多