i use typecast behavior in ActiveRecord class.
SQL
CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL,
`a` mediumint(8) unsigned DEFAULT NULL,
`b` tinyint(4) unsigned NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8;
INSERT INTO `test` (`id`, `a`, `b`) VALUES
(1, 123, 1),
(9999, 1, 11);
ALTER TABLE `test`
ADD PRIMARY KEY (`id`);
Class Test
use yii;
use yii\behaviors\AttributeTypecastBehavior;
class Test extends yii\db\ActiveRecord{
const TBL_NAME = 'test';
public static function tableName(){
return self::TBL_NAME;
}
public function behaviors(){
return [
'typecast' => [
'class' => AttributeTypecastBehavior::className(),
'attributeTypes' => [
'a' => AttributeTypecastBehavior::TYPE_INTEGER,
'b' => AttributeTypecastBehavior::TYPE_INTEGER,
],
'typecastAfterFind' => true,
],
];
}
}
Run
public function actionIndex(){
$obj = Test::find()->select('id,a')->one();
$obj->a = rand(1,9999);
$obj->save();
}
Yii2 Query
UPDATE `test` SET `a`='860', `b`=NULL WHERE `id`=1
UPDATE `test` SET `a`='860' WHERE `id`=1
UPDATE `test` SET `a`='860', `b`=NULL WHERE `id`=1
| Q | A
| ---------------- | ---
| Yii version | 2.0.10
| PHP version | 5.6.3
| Operating system | Win 8.1
You should disable AttributeTypecastBehavior::$skipOnNull if you wish null values to be typecasted as well.
You should disable AttributeTypecastBehavior::$skipOnNull if you wish null values to be typecasted as well.
no, my problem not solving.
Please note, in my example (Run section), i selected id and a column but not selected b column.
so when changed a column value and call save() yii2 only must be save a column but a and b column both updated.
when i removed AttributeTypecastBehavior from my class Test and run this example, Yii2 only save a column.
in all section of project have a this problem.(after added this behavior)
this is a bug.
You should remove b from attributeTypes then.
You should remove b from attributeTypes then.
i cant remove b from attributeTypes . the above example only is test but in my real project my id(pk) is int unsigned and more datatype in my project is unsigned and cant remove this columns.
if i use int(signed) , i not have a problem.
if i can't use attributeTypes with save() method, why i used this new feature in yii 2.0.10 ? :X(
i think find this problem in yii2.
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#dirty-attributes
please see
public function actionIndex(){
$obj = Test::find()->select('id,a')->one();
var_dump($obj->getDirtyAttributes()); # <--- array(2) { ["a"]=> int(2397) ["b"]=> NULL }
$obj->a = rand(1,9999);
$obj->save();
}
seems getDirtyAttributes() method, does not work.
Resolved by commit e7c080594d5d063397b76e413ee02a82ec690a62
Most helpful comment
Resolved by commit e7c080594d5d063397b76e413ee02a82ec690a62