yii2 Active record inserts empty row

时间:2016-04-04 16:43:28

标签: activerecord yii2

taking some troble with yii2 Active record. It does not want to insert data into the table. It just insert null`s Please, advice

table:

CREATE TABLE projects (
  p_id int(11) NOT NULL AUTO_INCREMENT,
  p_name varchar(50) DEFAULT NULL,
  p_create_date datetime DEFAULT NULL,
  p_last_update datetime DEFAULT NULL,
  p_active tinyint(4) DEFAULT NULL,
  p_comment varchar(255) DEFAULT NULL,
  PRIMARY KEY (p_id)
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;

code:

use yii\db\ActiveRecord;

class Projects extends ActiveRecord
{
    public $p_id;
    public $p_name;
    public $p_comment;
    public $p_create_date;
    public $p_last_update;
    public $p_active;

}

usage

$project = new Projects();
$project->p_name = 'asdfasdfasdf';
$project->save();

result https://monosnap.com/file/272s92Z5oQkNXWEZc7lO2lExLgDZS2

after ->save(), projects object looks like

object(app\models\Projects)#78 (14) {
    ["p_id"]=>
    NULL
    ["p_name"]=>
    string(9) "asdasdasd"
    ["p_comment"]=>
    NULL
    ["p_create_date"]=>
    NULL
    ["p_last_update"]=>
    NULL
    ["p_active"]=>
    NULL
    ["_attributes":"yii\db\BaseActiveRecord":private]=>
    array(1) {
      ["p_id"]=>
      int(19)
    }
    ["_oldAttributes":"yii\db\BaseActiveRecord":private]=>
    array(1) {
      ["p_id"]=>
      int(19)
    }
    ["_related":"yii\db\BaseActiveRecord":private]=>
    array(0) {
    }
    ["_errors":"yii\base\Model":private]=>
    array(0) {
    }
    ["_validators":"yii\base\Model":private]=>
    object(ArrayObject)#80 (1) {
      ["storage":"ArrayObject":private]=>
      array(0) {
      }
    }
    ["_scenario":"yii\base\Model":private]=>
    string(7) "default"
    ["_events":"yii\base\Component":private]=>
    array(0) {
    }
    ["_behaviors":"yii\base\Component":private]=>
    array(0) {
    }
  }

2 个答案:

答案 0 :(得分:2)

You must remove (or comment like below) the public var you added to the model ..

use yii\db\ActiveRecord;

class Projects extends ActiveRecord
{
   /*  public $p_id;
       public $p_name;
       public $p_comment;
       public $p_create_date;
       public $p_last_update;
       public $p_active; 
   */
  public function rules()
    {
        return [
            [['p_create_date', 'p_last_update', 'p_active'], 'safe',],
            [['codice_istat_comune_alfanum'], 'string', 'max' => 6],
            [['p_name', ], 'string', 'max' => 64],
            [['p_comment'], 'string', 'max' => 255]
        ];
    }



}

the public var you added shadow/override the original var created by yii2 active record saving in db

you should add public var to the model only for calculated value and never for db value

答案 1 :(得分:0)

Check validation errors:

$model->validate();
var_dump($model->errors);

If you have validation errors, model will not be saved.