YII框架常用技巧总结(2)
校验 point_template_id 在 PointTemplate 是否存在
public function rules()
{
return [
[['point_template_id'], 'exist',
'targetClass' => PointTemplate::className(),
'targetAttribute' => 'id',
'message' => '此{attribute}不存在。'
],
];
}
Yii给必填项加星
div . required label:after {
content:
" *";
color:
red;
}
执行SQL查询并缓存结果
$styleId = Yii::$app->request->get('style');
$collection = Yii::$app->db->cache(function ($db) use ($styleId) {
return Collection::findOne(['style_id' => $styleId]);
}, self::SECONDS_IN_MINITUE * 10);
场景:
数据库有user表有个avatar_path字段用来保存用户头像路径
需求: 头像url需要通过域名http://b.com/作为基本url
目标: 提高代码复用
此处http://b.com/可以做成一个配置
示例:
User.php
class User extends \yii\db\ActiveRecord
{
...
public function extraFields()
{
$fields = parent::extraFields();
$fields['avatar_url'] = function () {
return empty($this->avatar_path) ? '可以设置一个默认的头像地址' : 'http://b.com/' . $this->avatar_path;
};
return $fields;
}
...
}
ExampleController.php
class ExampleController extends \yii\web\Controller
{
public function actionIndex()
{
$userModel = User::find()->one();
$userData = $userModel->toArray([], ['avatar_url']);
echo $userData['avatar_url']; // 输出内容: http://b.com/头像路径
}
}
Model 里面 rules 联合唯一规则
复制代码 代码如下:
[['store_id', 'member_name'], 'unique', 'targetAttribute' => ['store_id', 'member_name'], 'message' => 'The combination of Store ID and Member Name has already been taken.'],
Model多个字段一条规则不同提示
[['name', 'email', 'subject', 'body'], 'required','message'=>'{attribute} 必须'],
标量查询
Post::find()->select('title')->where(['user_id' => $userId])->scalar();
生成 SQL:
SELECT `title` FROM `post` WHERE `user_id` = 1
直接输出 title 的值。
如果 select('title') 不写的话,生成 SQL 是:
`SELECT * FROM `post` WHERE `user_id`=1`
直接输出 id 的值
表单验证,去除首尾空格:
