我还有其他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';
}
答案 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'];
}
...