为什么这个ActiveRecord :: save成功保存模型?

时间:2016-05-19 11:50:11

标签: php yii yii2

$model-save()

返回true并将行添加到数据库。但我在数据库中没有字段默认值。怎么了?这是Action Controller和Scheme DB以及Model ActiveRecord

动作控制器

public function actionCreate()
{
    $model = new Requests();
    $model->user_id = null;

    if ($model->load(Yii::$app->request->post()) && $model->save()) {

        Yii::$app->response->format = Response::FORMAT_JSON;

        $response = [
            'id'  => $model->id,
            'url' => 'request-lease/'.$model->url,
        ];

        return $response;

    } else {
        return BaseHtml::errorSummary($model, ['class' => 'alert alert-danger']);
    }
}

模型ACtiveRecord

class Requests extends \yii\db\ActiveRecord
 {
/** Inactive status */
const STATUS_UNVERIFIED = 0;
/** Active status */
const STATUS_ACTIVE = 1;
/** Blocked status */
const STATUS_BLOCKED = 3;
/** Deleted status */
const STATUS_DELETED = 5;
/** Expired status */
const STATUS_EXPIRED = 6;

/**
 * Finance Array
 */
public static $trade_finance_arr = [
    1 => 'Leased',
    2 => 'Financed',
    3 => 'Owned',
    4 => 'Other'
];

/**
 * Trade condition array
 */
public static $trade_condition_arr = [
    1 => 'Excellent',
    2 => 'Good',
    3 => 'Fair',
    4 => 'Poor'
];


/**
 * @var string Model status.
 */
private $_status;

private $_credit_score;

public $offersCount;

/**
 * @inheritdoc
 */
public static function tableName()
{
    return '{{%carbuilder_requests}}';
}

/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'timestampBehavior' => [
            'class' => TimestampBehavior::className(),
        ],
    ];
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
//            [['user_id', 'vin', 'miles', 'zip', 'exterior_color', 'interior_color', 'comments', 'miles_per_year', 'started', 'term', 'credit_company', 'url', 'packages_ids', 'options_ids', 'created_at', 'updated_at', 'total_msrp', 'styleId'], 'required'],
        [['user_id', 'zip', 'miles_per_year', 'started', 'term',
            'credit_company', 'status_id', 'created_at', 'updated_at', 'total_msrp', 'styleId',
            'trade_finance','trade_bank','trade_term','trade_miles', 'trade_condition',
            'credit_score'], 'integer'],
        [['vin'], 'string', 'max' => 17],
        [['name', 'surname'], 'string', 'max' => 50],
        [['phone'], 'string', 'max' => 30],
        [['exterior_color', 'interior_color'], 'string', 'max' => 125],
        [['comments','trade_comments'], 'string', 'max' => 1000],
        [['url', 'pdf'], 'string', 'max' => 255],
        [['packages_ids', 'options_ids'], 'string', 'max' => 512],
        [['url'], 'unique'],
        [['income'], 'double']
        //[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'user_id' => 'User ID',
        'vin' => 'Vin',
        'trade_miles' => 'Miles',
        'zip' => 'Zip',
        'exterior_color' => 'Exterior Color',
        'interior_color' => 'Interior Color',
        'comments' => 'Comments',
        'miles_per_year' => 'Miles Per Year',
        'started' => 'Started',
        'term' => 'Term',
        'credit_company' => 'Credit Company',
        'url' => 'Url',
        'status_id' => 'Status ID',
        'packages_ids' => 'Packages Ids',
        'options_ids' => 'Options Ids',
        'created_at' => 'Created At',
        'updated_at' => 'Updated At',
        'total_msrp' => 'Total Msrp',
        'styleId' => 'Style ID',
        'pdf' => 'PDF',
        'activation_at' => 'Activation At'
    ];
}

/**
 * @inheritdoc
 */
public function beforeSave($insert)
{
    if ($insert) {
        if ($this->user_id === null) {
            $this->user_id = (Yii::$app->user->id) ? Yii::$app->user->id : 0;
        }
    }

    return parent::beforeSave($insert);
}

/**
 * @inheritdoc
 */
public function afterSave($insert, $changedAttributes)
{
    if ($insert) {
        $this->setUrl();
    }

    parent::afterSave($insert, $changedAttributes);
}

public static function findRequestbyUrl($node){


    return self::find()->where(['url'=>$node])->one();

}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOffers()
{
    return $this->hasMany(Offers::className(), ['request_id' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOffer()
{
    return $this->hasOne(Offers::className(), ['request_id' => 'id'])
        ->where(['user_id' => Yii::$app->user->id])
        ->inverseOf('request');
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getVehicle()
{
    return $this->hasOne(Vehicle::className(), ['styleId' => 'styleId']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getBank()
{
    return $this->hasOne(CreditCompany::className(), ['id' => 'trade_bank']);
}

/**
 * @return integer
 */
public function getNewCountMessages()
{
    $count = 0;
    foreach($this->offers as $offer) {
        $count += $offer->newCountMessages;
    }
    return $count;
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getPackages()
{
    if(empty($this->packages_ids)) return false;
    $packages = rtrim($this->packages_ids, ',');
    $packages = explode(',', $packages);
    return PackageOptions::find()->where(['optionsId' => $packages, 'styleId' => $this->styleId])->groupBy(['optionsId','styleId'])->all();
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getOptions()
{
    if(empty($this->options_ids)) return false;
    $options = rtrim($this->options_ids, ',');
    $options = explode(',', $options);
    return PackageOptions::find()->where(['optionsId' => $options, 'styleId' => $this->styleId])->groupBy(['optionsId','styleId'])->all();
}
/**
 * Change or create Request url
 * @param string|null $url Url of request
 * @return boolean true if lease url was successfully changed
 */
public function setUrl($url = null)
{
    if($url) {
        Route::saveUrl($url, 'carbuilder/requests/summary');
        $this->url = $url;
        return $this->save(false);
    }

    $url = Inflector::slug($this->vehicle->make . '-' . $this->vehicle->model . '-' . $this->vehicle->trim .  '-' . $this->vehicle->year . '-' . $this->exterior_color . '-' . $this->id );

    Route::saveUrl($url, 'carbuilder/requests/summary');
    $this->url = $url;
    return $this->save(false);
}
}

方案数据库

CREATE TABLE `lfl_carbuilder_requests` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `user_id` int(11) NOT NULL,
 `vin` varchar(17) NOT NULL,
 `zip` int(5) NOT NULL,
 `exterior_color` varchar(125) NOT NULL,
  `interior_color` varchar(125) NOT NULL,
  `comments` varchar(1000) NOT NULL,
  `miles_per_year` int(5) NOT NULL,
  `started` int(11) NOT NULL,
  `term` tinyint(2) NOT NULL,
  `credit_company` tinyint(4) NOT NULL,
  `url` varchar(255) NOT NULL,
  `status_id` tinyint(4) NOT NULL DEFAULT '0',
  `packages_ids` varchar(512) NOT NULL,
  `options_ids` varchar(512) NOT NULL,
  `created_at` int(11) NOT NULL,
  `updated_at` int(11) NOT NULL,
  `total_msrp` int(11) DEFAULT NULL,
  `styleId` varchar(20) NOT NULL,
  `pdf` varchar(255) NOT NULL,
  `trade_finance` int(2) NOT NULL,
  `trade_bank` int(4) NOT NULL,
  `trade_term` int(2) NOT NULL,
  `trade_miles` int(5) NOT NULL,
  `trade_condition` int(2) NOT NULL,
  `trade_comments` varchar(1000) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  `surname` varchar(50) DEFAULT NULL,
  `phone` varchar(30) DEFAULT NULL,
  `state` varchar(30) NOT NULL,
  `location` varchar(30) NOT NULL,
  `credit_score` tinyint(1) DEFAULT NULL,
  `income` double NOT NULL,
  `activation_at` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `url` (`url`),
  KEY `status_id` (`status_id`),
  KEY `styleId` (`styleId`),
  KEY `FK_users_requests` (`user_id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=661 DEFAULT CHARSET=utf8

发布请求

exterior_color:"Deep Sea Blue Metallic"
interior_color:"Aluminum Hexagon W/Estoril Blue Matte Highlight"
options_ids:""
packages_ids:"200744520"
request_id:0
styleId:200744434
total_msrp:41550
user_id:0

1 个答案:

答案 0 :(得分:0)

本答案认为只有你不发布其他人提交的id字段。

在您的数据库中Id是自动增量

`id` int(11) NOT NULL AUTO_INCREMENT,

这就是为什么它按前一个值递增并返回id

其次,如果您在表单选择框和单选按钮中使用它,则采用默认值。