mra*_*teb 4 php mysql yii yii2
在Yii2中,我有一个模型,例如Product.我想要做的是从数据库中选择一个额外的列作为int
这是我正在做的一个例子:
Product::find()->select(['id', new Expression('20 as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
Run Code Online (Sandbox Code Playgroud)
问题是,我得到的结果为"20".换句话说,20作为字符串返回.如何确保所选的是整数?
我也试过以下但它不起作用:
Product::find()->select(['id', new Expression('CAST(20 AS UNSIGNED) as type')])
->where(['client' => $clientId])
->andWhere(['<>', 'hidden', 0]);
Run Code Online (Sandbox Code Playgroud)
您可以手动强制转换Product的afterFind()功能或用途AttributeTypecastBehavior.
但最重要的是,您必须attribute为查询中使用的别名定义自定义.例如,$selling_price在您的Product模型中,如果您将其selling _price用作别名.
public $selling_price;
Run Code Online (Sandbox Code Playgroud)
之后,您可以使用以下任何一种方法.
1) afterFind
以下示例
public function afterFind() {
parent::afterFind();
$this->selling_price = (int) $this->selling_price;
}
Run Code Online (Sandbox Code Playgroud)
以下示例
public function behaviors()
{
return [
'typecast' => [
'class' => \yii\behaviors\AttributeTypecastBehavior::className(),
'attributeTypes' => [
'selling_price' => \yii\behaviors\AttributeTypecastBehavior::TYPE_INTEGER,
],
'typecastAfterValidate' => false,
'typecastBeforeSave' => false,
'typecastAfterFind' => true,
],
];
}
Run Code Online (Sandbox Code Playgroud)