Returning raw query as array yii 2

萝らか妹 提交于 2020-01-05 05:32:52

问题


Hello how do I return a raw query into an array in yii 2? I have been working on this code and I assume that it should return multiple rows but when I try to a foreach on a view it it says that Invalid argument supplied for foreach()

Here is the error page:

Here is the code I am working on

Model

  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();
  }

View

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

回答1:


You should simply use queryAll() instead of execute() :

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

About execute() :

This method should only be used for executing non-query SQL statement, such as INSERT, DELETE, UPDATE SQLs. No result set will be returned.

About queryAll() :

Executes the SQL statement and returns ALL rows at once.



来源:https://stackoverflow.com/questions/39343269/returning-raw-query-as-array-yii-2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!