新增
使用 model::save()
操作进行新增数据
$user = new User;$user->username = $username;$user->password = $password;$user->save()
使用 createCommand()
进行新增数据
Yii::$app->db->createCommand()->insert('user', [ 'name' => 'test', 'age' => 30,])->execute();
批量插入数据
Yii::$app->db->createCommand()->batchInsert('user', ['name', 'age'], [ ['test01', 30], ['test02', 20], ['test03', 25],])->execute();
修改
使用 model::save()
进行修改
$user = User::find()->where(['name' => 'test'])->one(); // 获取 name 等于 test 的模型$user->age = 40; // 修改 age 属性值$user->save(); // 保存
直接修改:修改用户 test
的年龄为 40
$result = User::model()->updateAll(['age' => 40],['name' => 'test']);
使用 createCommand()
修改
Yii::$app->db->createCommand()->update('user', ['age' => 40], 'name => test')->execute();
删除
使用 model::delete()
进行删除
$user = User::find()->where(['name' = >'test'])->one();$user->delete();
直接删除:删除年龄为30的所有用户
$result = User::deleteAll(['age' = >'30']);
使用 createCommand()
删除
Yii::$app->db->createCommand()->delete('user', 'age = 30')->execute();
1、首先要在所需要使用验证码的控制器里配置下actions方法。
public function actions() { return [ 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'backColor'=>0x000000,//背景颜色 'maxLength' => 6, //最大显示个数 'minLength' => 5,//最少显示个数 'height'=>35,//高度 'width' => 130, //宽度 'foreColor'=>0xffffff, //字体颜色 'offset'=>4, //设置字符偏移量 有效果 //'controller'=>'login', //拥有这个动作的controller ], ]; }
2、View层增加验证码的filed。
echo $form->field($model, 'verifyCode')->widget(Captcha::className(), [ 'template' => '<div class="row"><div class="col-lg-5">{input}</div><div class="col-lg-5">{image}</div></div>', ])
使用migration备份和还原数据库,最初只想做一个在命令行中备份的功能,后来将类重组了,增加了其他扩展使用方法。
安装此扩展的首选方式是通过 composer.
运行
composer require --prefer-dist e282486518/yii2-console-migration "*"
或者添加
"e282486518/yii2-console-migration": "*"
到 composer.json
文件的对应地方.
在console\config\main.php
中添加 :
'controllerMap' => [ 'migrates' => [ 'class' => 'e282486518\migration\ConsoleController', ], ],
在命令行中使用方式:
php ./yii migrates/backup all #备份全部表 php ./yii migrates/backup table1,table2,table3... #备份多张表 php ./yii migrates/backup table1 #备份一张表 php ./yii migrates/up #恢复全部表
利用事件给信息记录点击率
控制器页面代码
const VIEW_EVENT = 'event'; //定义事件名 public function init() { parent::init(); $this->on(self::VIEW_EVENT,function(){ $id = Yii::$app->request->get('id'); //获取文章ID $article = new funModel(); //实例化数据模型 $article->viewsNum($id); //数据模型方法 注意 funModel一定要有这个方法 }); }在 public function actionArticle($id){ $this->trigger(self::VIEW_EVENT);//触发调用事件 ............ }
funModel数据模型里面的代码
public function viewsNum($id){ $model = self::find()->where('id = :id',[':id'=>$id])->one(); $model->view = $model->view + 1; return $model->save()?true:false; }
Controller控制器层代码
<?php namespace frontend\controllers; use frontend\models\UserForm; class UserController extends \yii\web\Controller { public function actionIndex() { $model = new UserForm; if ($model->load(\Yii::$app->request->post()) && $model->validate()) { echo "通过"; } return $this->render('index',[ "model" => $model, ]); } }
yii2 SQLSTATE[HY000] [2002] Connection refused
就上面这个问题,各种搜索,各种查找,总结两个方案
1、linux下localhost替换成127.0.0.1
2、上面不能解决请更换空间商提供的mysql远程链接地址。
希望能帮到你
'db' => [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=127.0.0.1;dbname=数据库名', 'username' => '数据库用户名', 'password' => '数据库密码', 'charset' => 'utf8', ],
ActiveForm、Breadcrumbs、DetailView、LinkPager、ListView 等等,这些内置的挂件让我们开发变的如此简单。
本节教你自定义一个widget,顺便说下widget的运行机理和几大重要函数。
老规矩,先说目录。
什么时候用widget
新建一个widget
begin & end 方法
beforeRun & afterRun 方法
begin...
场景还是蛮简单的、当我们发现页面有的区块重复出现了,比如TOP10、比如内容编辑器等、就要考虑是否要做成一个widget了。
我们还是举例把,新建一个Top10的区块。首先我们要在应用程序的components下新建一个Top10Widget的类,根据psr-4规则,布局应该是这样的
components
components\Top10Widget.php
Top10Widget.php的内容
namespace app\components;use yii\base\Widget;class Top10Widget extends Widget { public $catId; public function init(){ parent::init(); if(empty($this->catId)){ $this->catId = 0; } } public function run(){ parent::run(); } }
1、findOne()和findAll():
// 查询key值为10的客户 $customer = Customer::findOne(10); $customer = Customer::find()->where(['id' => 10])->one(); // 查询年龄为30,状态值为1的客户 $customer = Customer::findOne(['age' => 30, 'status' => 1]); $customer = Customer::find()->where(['age' => 30, 'status' => 1])->one(); // 查询key值为10的所有客户 $customers = Customer::findAll(10); $customers = Customer::find()->where(['id' => 10])->all(); // 查询key值为10,11,12的客户 $customers = Customer::findAll([10, 11, 12]); $customers = Customer::find()->where(['id' => [10, 11, 12]])->all(); // 查询年龄为30,状态值为1的所有客户 $customers = Customer::findAll(['age' => 30, 'status' => 1]); $customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
2、where条件
以下我用的标签都是php短标 <? ?>
文本框:
<? $model->username = '我是猪'?> <!--文本框默认选中--> <?= $form->field($model,'username')->textInput(/*['value'=>'我是猪']*/)?> <!--第二种用:value=>'值'-->
单选按钮:
<? $model->sex = '1'?> <!--单选框默认选中--> <?= $form->field($model,'sex')->radioList(['0'=>'男','1'=>'女'])?>
value值是1的为默认选中
多选框:
<? $model->hobby = ['iphone','sanxing' ] ?><!--多选框默认选中--> <?= $form->field($model,'hobby')->checkboxList(['sanxing'=>'三星','iphone'=>'苹果','vivo'=>'步步高'])?>
value值为 ipgone , sanxing 将为默认选中
下拉框:
<? $model->news_classify = 2 ?> <!--下拉菜单默认选中--> <?= $form->field($model,'news_classify')->dropDownList($arr)?>
key值为2的 将默认选中
或者用另外一种方法 这边要用到 prompt 关键字
<?= $form->field($model,'news_classify')->dropDownList($arr,[‘prompt’ => $arr[2]])?>
<?= $form->field($model, 'description')->textArea(['rows' => '6']) ?> <?= Html::submitButton('Submit') ?> <?php ActiveForm::end(); ?>
官方资料:
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html
http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
一些补充
activecontroller的各种action是可以重载的,但必须先要unset掉父类的方法。
比如下面这样,注意里面的actions()方法,如果这里没有unset掉父类方法的话,重载的function actionXXX不会起作用。
<?php namespace app\modules\rest\v2\controllers; use Yii; use yii\data\ActiveDataProvider; use app\models\db\Task; use app\models\db\TaskSearch; class TaskController extends BaseActiveController { public $modelClass = 'app\models\db\Task'; public function actions() { $actions = parent::actions(); unset($actions['index']); return $actions; } public function actionIndex() { $searchModel = new TaskSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); return $dataProvider; } }
安装插件composer里面下载安装
用法:
控制器(Controller)需要先调用
public function actions() { return [ 'upload' => [ 'class' => 'kucha\ueditor\UEditorAction', ] ]; }
视图(view)页面调用方法
$form->field($model,'content')->widget(UEditor::className(),['clientOptions'=> [ 'toolbars'=>[ ['fullscreen', 'source', 'undo', 'redo', 'bold', 'italic', 'underline', 'fontborder', 'backcolor', 'fontsize', 'fontfamily', 'justifyleft', 'justifyright', 'justifycenter', 'justifyjustify', 'strikethrough', 'superscript', 'subscript','removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor','insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', 'link', 'unlink', 'emotion', 'help' ] ] ] ]);
<?php $form = ActiveForm::begin([ 'options'=>['enctype'=>'multipart/form-data','class' => 'form-horizontal'], 'fieldConfig' => [ //统一修改字段的模板 'template' => "{label}\n<div class=\"col-lg-5\">{input}</div>\n<div class=\"col-lg-3\">{error}</div>", //修改显示内容默认为{label}\n{input}\n{hint}\n{error} \n是html代码显示时的换行 'labelOptions' => ['class' => 'col-lg-2 control-label'], //修改label的样式 ], ]); ?>
<?= $form->field($model, 'img_path',[ 'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-2\"><label for=\"uploadImg\" class=\"btn btn-default forfocus1\" onclick=\"changeImg(1,'forfocus');\">选择图片<img src=\"\"></label></div>\n{error}", 'labelOptions' => ['class' => 'col-lg-2 control-label'], ])->textInput(['maxlength' => 255,'placeholder'=>'专题图片','readonly'=>true])->label('专题名称')->hint('错误提示信息') ?>
<?php $form = ActiveForm::begin([ 'options'=>['enctype'=>'multipart/form-data','class' => 'form-horizontal'], 'fieldConfig' => [ 'template' => "{label}\n<div class=\"col-lg-5\">{input}</div>\n<div class=\"col-lg-5\">{error}</div>", 'labelOptions' => ['class' => 'col-lg-2 control-label'], ], ]); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => 255,'placeholder'=>'请输入专题名称'])->label('专题名称') ?> <?= $form->field($model, 'img_path',[ 'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-2\"><label for=\"uploadImg\" class=\"btn btn-default forfocus1\" onclick=\"changeImg(1,'forfocus');\">选择图片<img src=\"\"></label></div>\n{error}", 'labelOptions' => ['class' => 'col-lg-2 control-label'], ])->textInput(['id'=>'img_path','maxlength' => 255,'placeholder'=>'专题图片','readonly'=>true])->label('专题名称') ?> <?= $form->field($model, 'showImg',[ 'template' => "{label}\n<div id=\"showImg\" class='col-lg-10'></div>", 'labelOptions' => ['class' => 'col-lg-2 control-label'], ])->label('图片预览') ?> <?= $form->field($model, 'link_to')->textInput(['maxlength' => 255,'placeholder'=>'请输入专题链接'])->label('专题链接') ?> </div> <div class="form-group" style="margin-left: 50px;"> <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> </div> <?php ActiveForm::end(); ?>
$this->params['breadcrumbs'][] = ['label'=>$title.' -- ','url'=>Url::to(['index/newlist'])]; 带连接 $this->params['breadcrumbs'][] = '正文'; 不带链接 yii2一个页面两个验证码效验问题 http://blog.csdn.net/xiaoxiong_web/article/details/77159673
在应用的时候需要先对yii2进行扩展安装
如果装有composer直接运行
php composer.phar require --prefer-dist yiisoft/yii2-redis
当然也可以本地安装
下载yii2-redis扩展包(https://github.com/yiisoft/yii2-redis )并解压
将解压后的文件移至vebdor/yiisoft命名为yii2-redis
打开vebdor/yiisoft下的extensions.php
添加如下代码
'yiisoft/yii2-redis' => array ( 'name' => 'yiisoft/yii2-redis', 'version' => '2.0.5.0', 'alias' => array ( '@yii/redis' => $vendorDir . '/yiisoft/yii2-redis', ), ),
最后在config文件下的web.php中添加如下配置项(配置文件目录要写对笔者当时就是因为这个搞错了浪费了一上午时间)
'redis' =>[ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', //你的redis地址 'port' => 6379, //端口 'database' => 0, ]
接下来就可以进行对redis的操作了
对象操作查询[php]
//1.简单查询 $admin=Admin::model()->findAll($condition,$params); $admin=Admin::model()->findAll("username=:name",array(":name"=>$username)); $infoArr= NewsList::model()->findAll("status = '1' ORDER BY id DESC limit 10 "); //2. findAllByPk(该方法是根据主键查询一个集合,可以使用多个主键) $admin=Admin::model()->findAllByPk($postIDs,$condition,$params); $admin=Admin::model()->findAllByPk($id,"name like :name and age=:age",array(':name'=>$name,'age'=>$age)); $admin=Admin::model()->findAllByPk(array(1,2)); //3.findAllByAttributes (该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面) $admin=Admin::model()->findAllByAttributes($attributes,$condition,$params); $admin=Admin::model()->findAllByAttributes(array('username'=>'admin')); //4.findAllBySql (该方法是根据SQL语句查询一个数组) $admin=Admin::model()->findAllBySql($sql,$params); $admin=Admin::model()->findAllBySql("select * from admin where username like :name",array(':name'=>'%ad%')); User::find()->all(); 此方法返回所有数据; User::findOne($id); 此方法返回 主键 id=1 的一条数据(举个例子); User::find()->where(['name' => '小伙儿'])->one(); 此方法返回 ['name' => '小伙儿'] 的一条数据; User::find()->where(['name' => '小伙儿'])->all(); 此方法返回 ['name' => '小伙儿'] 的所有数据; User::find()->orderBy('id DESC')->all(); 此方法是排序查询; User::findBySql('SELECT * FROM user')->all(); 此方法是用 sql 语句查询 user 表里面的所有数据; User::findBySql('SELECT * FROM user')->one(); 此方法是用 sql 语句查询 user 表里面的一条数据; User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id'); 统计符合条件的总条数; User::find()->one(); 此方法返回一条数据; User::find()->all(); 此方法返回所有数据; User::find()->count(); 此方法返回记录的数量; User::find()->average(); 此方法返回指定列的平均值; User::find()->min(); 此方法返回指定列的最小值 ; User::find()->max(); 此方法返回指定列的最大值 ; User::find()->scalar(); 此方法返回值的第一行第一列的查询结果; User::find()->column(); 此方法返回查询结果中的第一列的值; User::find()->exists(); 此方法返回一个值指示是否包含查询结果的数据行; User::find()->batch(10); 每次取 10 条数据 User::find()->each(10); 每次取 10 条数据, 迭代查询