当id字段未命名为id

时间:2016-01-24 18:41:37

标签: php yii2

我还有其他api工作,但我刚刚添加了一个表{id}字段而不是user_id的表,现在api说找不到该对象。有没有办法覆盖api用id寻找的字段?

日志通常会在userinfos/1

中说明这一点
users/12

我为SELECT * FROM `user` WHERE `id`='12' 收到此错误,因为id实际上是user_info表中的user_id:

userinfos/12

应该说exception 'yii\web\NotFoundHttpException' with message 'Object not found: 12' in /opt/decathletics/vendor/yiisoft/yii2/rest/Action.php:101 ,但我得到了上述错误

UserinfoController.php

SELECT * FROM user_info WHERE user_id='12'

UserInfo.php模型

<?php

namespace api\modules\v1\controllers;

use Yii; 
use yii\rest\ActiveController;
use yii\filters\auth\HttpBasicAuth;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\User;
use api\modules\v1\models\UserInfo;

class UserinfoController extends ActiveController
{

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => HttpBasicAuth::className(),
        ];
        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'roles' => ['@'],
                    'matchCallback' => function ($rule, $action) {
                        return Yii::$app->user->id == Yii::$app->request->get('id');
                    },
                    'verbs' => ['GET','PUT']
                ],
            ],
        ];
        return $behaviors;
    }

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

}

1 个答案:

答案 0 :(得分:2)

ActiveController 将使用yii\rest\Action::findModel($id)根据数据库表中声明的模型主键来获取数据。在您的情况下,您可以尝试检查数据库架构,看看user_id是否真的被定义为user_info表的主键(而不是id),或者您可以尝试手动覆盖您的模型primaryKey()方法添加以下内容:

class UserInfo extends \yii\db\ActiveRecord
{
  ...

  public static function primaryKey()
  {
     return ['user_id'];
  }

  ...