2016-09-06 65 views
0

你好,我如何返回一個原始查詢到yii 2中的數組?我一直在這個代碼,我認爲它應該返回多行,但是當我嘗試在一個視圖中的foreach它,它說的是對的foreach()返回原始查詢作爲數組yii 2

這裏提供了無效的說法是錯誤頁面:

enter image description here

這裏是我的

型號

public function Showprerequisites($trno){ 
    // $connection = Yii::$app->GetDb(); 

    return Yii::$app->db->CreateCommand(' 

    SELECT * FROM 
(
SELECT pre1 AS col FROM ccsubject WHERE trno = 29005 AND pre1 IS NOT NULL 
UNION 
SELECT pre2 AS col FROM ccsubject WHERE trno = 29005 AND pre2 IS NOT NULL 
UNION 
SELECT pre3 AS col FROM ccsubject WHERE trno = 29005 AND pre3 IS NOT NULL 
UNION 
SELECT pre4 As col FROM ccsubject WHERE trno = 29005 AND pre4 IS NOT NULL 
UNION 
SELECT pre5 AS col FROM ccsubject WHERE trno = 29005 AND pre5 IS NOT NULL 
) T1 

    ')->execute(); 
    } 

查看工作代碼

$preq = TestController::Showprerequisites(29005); 
foreach($preq as $values){ 
    echo $values['col']; 
} 

回答

2

您只需要使用queryAll()代替execute()

return Yii::$app->db->CreateCommand('SELECT...')->queryAll(); 

關於execute()

此方法僅用於執行非查詢SQL語句,比如INSERTDELETEUPDATE SQLs。沒有結果集將被返回。

關於queryAll()

執行SQL語句,並同時返回所有行。