我正在努力学习yii并创建一个api。我能够获取数据,但我无法使用我的json对象创建新记录。
这就是我得到的
这是我在api配置中的main.php看起来像
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php')
);
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'api\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'user' => [
'identityClass' => '\common\models\User',
'enableSession' => false,
'loginUrl' => null
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'AH7T3J6-nwgUOF3DK_MYPhyzhhguo5-k',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
]
],
],
'params' => $params,
];
如您所见,我正在请求中设置json解析器。
这是模型
<?php
namespace common\models;
use Yii;
/**
* This is the model class for table "room".
*
* @property integer $id
* @property integer $floor
* @property integer $room_number
* @property integer $has_conditioner
* @property integer $has_tv
* @property integer $has_phone
* @property string $available_from
* @property string $price_per_day
* @property string $description
*/
class Room extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'room';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone', 'available_from'], 'required'],
[['floor', 'room_number', 'has_conditioner', 'has_tv', 'has_phone'], 'integer'],
[['available_from'], 'safe'],
[['price_per_day'], 'number'],
[['description'], 'string'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'floor' => 'Floor',
'room_number' => 'Room Number',
'has_conditioner' => 'Has Conditioner',
'has_tv' => 'Has Tv',
'has_phone' => 'Has Phone',
'available_from' => 'Available From',
'price_per_day' => 'Price Per Day',
'description' => 'Description',
];
}
}
由于某些原因,它只是没有得到json格式。
我尝试使用表单数据,它似乎有效。但只是原始的json不会工作
请看这里