做者:白狼 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(); }