我尝试从此http://budiirawan.com/setup-restful-api-yii2/安装RESTful API模块,但我收到错误
找不到对象!
我尝试设置mod_rewrite
和AllowOverride All
配置。
我还将它连接到正确的数据库,并且该数据库中包含country
表。
我还有.htaccess
个文件,这里是我的api/config/main.php
文件
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'modules' => [
'v1' => [
'basePath' => '@app/modules/v1',
'class' => 'api\modules\v1\Module'
]
],
'components' => [
'user' => [
'identityClass' => 'common\models\User',
'enableAutoLogin' => false,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
],
'params' => $params,
];
以下是模型Country
<?php
namespace api\modules\v1\models;
use yii\db\ActiveRecord;
/**
* Country Model
*
* @author Budi Irawan <deerawan@gmail.com>
*/
class Country extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'country';
}
/**
* We use the primary function because we don't use integer auto increment as a primary key.
* @inheritdoc
*/
public static function primaryKey()
{
return ['code'];
}
/**
* To let Yii know what fields exist on the table.
* Define rules for validation
*/
public function rules()
{
return [
[['code', 'name', 'population'], 'required']
];
}
}
通过http://localhost/yii2-api/api/v1/countries访问时,我仍然遇到同样的错误。
答案 0 :(得分:2)
根据教程,你必须使用url:
http://localhost/yii2-api/api/web/v1/countries
而不是
http://localhost/yii2-api/api/v1/countries
答案 1 :(得分:0)
就我而言, mysql表具有复合主键(错误制作), 并且只有GET / v1 / othertable / 1失败,并出现此错误,而其他路由仍在工作。 当我通过PhpMyAdmin对索引进行排序时,它开始起作用。