yii2开发遇到的常见问题以及解决方案

博主推荐:yii2实战式教程是一套幽默风趣的高质量教程,从 yii2基础入门 到 yii2高级进阶,正在火热持续更新中,让你不错过yii2的每一个技术干货。

yii2 遇到的问题解决

1、测试项目列表,id搜索,显示

1052 Column "id" in where clause is ambiguous
The SQL being executed was:
SELECT COUNT(*) FROM `a` LEFT JOIN `b` ON `a`.`id` = `b`.`id` WHERE `id`=1

解决方式:

ASearch.php search方法关于id的搜索前面增加表名

//当前表a,关联表 b

$query = a::find();
$query->joinWith(["b"]);
......
$query->andFilterWhere([   
    ......
    "a.id" => $this->id, //注意到这里id前面添加表名以便区分哪个表的id
    ...... //其他代码照写
]);

2、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)
{
    ......
}

3、DetailView,显示的内容添加链接可以跳转,类文件同问题2,解决犯案如下:

DetailView::widget([
    "model" => $model,
    "attributes" => [
        ......
        [
            "attribute" => "用户",
            "format" => "raw",
            "value" => Html::a($model->name, ["/url", "id" => $model->id]),
        ],
    ],
]);

4、yii2脚本自动执行的时候,服务器上执行crontab -e 打开文件添加执行命令即可

5、问题:取分组中每组中最新的数据

原解决方案(效率很低)

select `id`, `relation_id`, `created_at` 
from `a` 
where `id` in (
select SUBSTRING_INDEX(GROUP_CONCAT(`id` order by `id` desc),",",1) 
FROM `a`
 where `uid` = 100 
group by `relation_id`
) 
order by `id` desc

优化方案(仍然很慢,但是有效果)

select `id`, `relation_id`, `created_at` 
from `a` 
where `id` in (
select max(`id`) FROM `a` where `uid` = 100 group by `relation_id`
)
order by `id` desc

二次优化方案(拆分sql)

$db = Yii::app()->db;
$sql = "select max(`id`) `m` FROM `a` where `uid` = 100 group by `relation_id`;
$res = $db->createCommand($sql)->queryAll();
$temp = "";
if ($res){
    foreach ($res as $v)
    {
        $temp .= $v["m"].",";
    }
    $temp = rtrim($temp, ",")
    $sql = "select `id`, `relation_id`, `created_at` from `a` where `id` in ({$temp}) order by `id` desc";
    $lastInfo = $db->createCommand($sql)->queryAll();
 }";

关于问题:取分组中每组中最新的数据,暂时仍没找到好的解决方案,如果你有好的解决方案,欢迎留言。

6、yii2因post常见的400错误

首先是post操作,基本上都是自己写的表单没有添加csrf报的400错误,添加一个隐藏域即可

<?= Html::hiddenInput('_csrf', Yii::$app->request->csrfToken) ?>

感觉本篇文章不错,对你有收获?

¥ 我要小额赞助,鼓励作者写出更好的教程
作者 白狼
本文版权归作者,欢迎转载,但未经作者同意必须保留 此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。