You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Yii1中非主键关联查询:获取ar_code时Array to string转换报错解决

Fixing "Array to string conversion" Error in Yii1's CDetailView

You're seeing this error in your CDetailView:

[error] [php] Array to string conversion (D:\Xampp\htdocs\framework\yii1.1.19\zii\widgets\CDetailView.php:240)

Let's break down why this is happening and how to fix it quickly:

Root Cause

Your getAR_code() method uses queryAll(), which returns an array of associative arrays (even if there's only one matching record from ar_codes). But CDetailView expects the value property to be a string (or a value that can be automatically cast to a string). When it tries to convert the array to a string, PHP throws that error.

Solutions

You have two straightforward ways to resolve this:

1. Modify the Model Method to Return a String Value

Since you only need the ar_code field, there's no reason to return a full array set. Use queryScalar() to get the single value directly:

public static function getAR_code($actId) {
    return Yii::app()->db->createCommand()
        ->select('ar_code')
        ->from('{{ar_codes}}')
        ->where('act_id=:actId', [':actId' => (int)$actId]) // Use parameter binding for security
        ->queryScalar(); // Returns the first matching ar_code, or null if none exists
}

If multiple ar_code entries match the same act_id, use queryColumn() to get an array of codes, then join them into a readable string:

public static function getAR_code($actId) {
    $codes = Yii::app()->db->createCommand()
        ->select('ar_code')
        ->from('{{ar_codes}}')
        ->where('act_id=:actId', [':actId' => (int)$actId])
        ->queryColumn();
    
    return empty($codes) ? 'No codes found' : implode(', ', $codes);
}

2. Handle the Array Directly in CDetailView

If you don't want to adjust the model method, you can process the array right in the value field using an anonymous function (Yii 1.1 supports this syntax):

array(
    'name' => 'actId',
    'type'=> 'raw',
    'value' => function($model) {
        $codeData = ActivityRecord::getAR_code($model->actId);
        // Return the first matching code if only one is needed
        return !empty($codeData) ? $codeData[0]['ar_code'] : 'No code found';
        // To display multiple codes separated by commas:
        // return !empty($codeData) ? implode(', ', array_column($codeData, 'ar_code')) : 'No codes found';
    },
    'htmlOptions' => array('style' => "text-align:left;"),
),

Quick Security Tip

I used parameter binding (:actId) in the examples instead of directly concatenating $actId into the query. This prevents SQL injection attacks, which is critical especially if $actId comes from user input.

内容的提问来源于stack exchange,提问作者Raihanul Hoque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:35