做者:白狼 php
出处:http://www.manks.top/article/yii2_common_problem_resolve html
本文版权归做者,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接,不然保留追究法律责任的权利。sql
yii2 遇到的问题解决服务器
一、测试项目列表,id搜索,显示
yii2
1052 Column 'id' in where clause is ambiguous The SQL being executed was: SELECT COUNT(*) FROM `test_items` LEFT JOIN `test_cat` ON `test_items`.`test_cat_id` = `test_cat`.`id` WHERE `id`=‘1'
解决方式:app
TestItemsSearch.php search方法关于id的搜索前面增长表名,yii
//当前表 test_items,链接表 test_cat $query = TestItems::find(); $query->joinWith(['testCat']); ...... $query->andFilterWhere([ 'test_items.id' => $this->id, //注意到这里id前面添加表名以便区分哪一个表的id ...... //其余代码照写 ]);
二、DetailView ‘content:ntext’,这种的attribute带标签,可是在DetailView就是想按照html的样式显示,怎么搞喃?测试
<?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'desc:ntext', //gii 默认生成text字段: [ 'attribute' => 'desc', 'format' => 'html', //显示html样式的方案 'value' => $model->desc, ], ], ]) ?>
源码追踪:优化
//yii\widgets\DetailView; //yii\i18n\Formatter.php //查看DetailView,找到 yii\i18n\Formatter.php文件,各类format均可以解决: public function format($value, $format) { ...... $method = 'as' . $format; ...... } ...... public function asHtml($value, $config = null) { ...... }
三、DetailView,显示的内容添加连接能够跳转,类文件同问题2,解决犯案以下:
ui
DetailView::widget([ 'model' => $model, 'attributes' => [ ...... [ 'attribute' => '用户', 'format' => 'raw', 'value' => Html::a($model->name, ['user-login/view', 'id' => $model->uid]), ], ], ]);
四、yii2脚本自动执行的时候,服务器上执行crontab -e 打开文件添加执行命令便可
五、问题:取分组中每组中最新的数据
原解决方案(效率很低):
select `id`, `test_items_id`, `create_time`, `score` from `test_result` where id in (select SUBSTRING_INDEX(GROUP_CONCAT(id order by `id` desc),',',1) FROM `test_result` where `uid` = {$uid} group by test_items_id ) order by `id` desc
优化方案(仍然很慢,可是有效果):
select `id`, `test_items_id`, `create_time`, `score` from `test_result` where id in (select max(id) FROM `test_result` where `uid` = {$uid} group by test_items_id ) order by `id` desc
二次优化方案(拆分sql):
$db = Yii::app()->db; $sql = "select max(`id`) m FROM `test_result` where `uid` = {$uid} group by `test_items_id`;$res = $db->createCommand($sql)->queryAll(); $temp = ''; if ($res) { foreach ($res as $v) { $temp .= $v['m'].','; } $temp = rtrim($temp, ','); $sql = "select `id`, `test_items_id`, `create_time`, `score` from `test_result` where id in ({$temp}) order by `id` desc"; $lastInfo = $db->createCommand($sql)->queryAll(); }