将Yii2 php stdClass()对象转换为特定类的对象
我从MySql查询中得到了一个数组,我所做的就是将它转换为object。但在转换成object之后,它就变成了stdClass()的对象,所以我希望它成为主题类的对象 我的密码将Yii2 php stdClass()对象转换为特定类的对象,php,mysql,yii2,Php,Mysql,Yii2,我从MySql查询中得到了一个数组,我所做的就是将它转换为object。但在转换成object之后,它就变成了stdClass()的对象,所以我希望它成为主题类的对象 我的密码 public function actionIndex() { // $theme = Theme::find()->all(); $query = "SELECT t.*,COUNT(d.id) AS total_downloads FROM `themes` AS T
public function actionIndex()
{
// $theme = Theme::find()->all();
$query = "SELECT t.*,COUNT(d.id) AS total_downloads FROM `themes` AS T
LEFT JOIN downloads AS D
ON D.theme_id = T.id GROUP
by t.id ORDER BY total_downloads DESC LIMIT 6";
$connection=Yii::$app->db;
$trends = $connection->createCommand($query);
$model = $trends->queryAll();
return $this->render('index',[
'model'=>$model,
]);
}
查看代码看起来像
<?php foreach ($model as $themes): ?>
<?php $theme = (object) $themes; ?>
<?php var_dump($theme) ?>
<div class="col-md-4">
</div>
<?= $theme->name ?>
如何将
$model
转换为类Theme.php
的对象我在这里找到了一个解决方案
function cast($destination, $sourceObject)
{
if (is_string($destination)) {
$destination = new $destination();
}
$sourceReflection = new ReflectionObject($sourceObject);
$destinationReflection = new ReflectionObject($destination);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$sourceProperty->setAccessible(true);
$name = $sourceProperty->getName();
$value = $sourceProperty->getValue($sourceObject);
if ($destinationReflection->hasProperty($name)) {
$propDest = $destinationReflection->getProperty($name);
$propDest->setAccessible(true);
$propDest->setValue($destination,$value);
} else {
$destination->$name = $value;
}
}
return $destination;
然后像这样调用函数
<?php
use yii\helpers\Html;
$theme_obj = new \common\models\Theme();
use common\Constant;
?>
<?php foreach ($model as $themes): ?>
<?php $theme = (object) $themes; ?>
<?php var_dump(Constant::cast($theme_obj , $theme)) ?>
<?php endforeach ?>
它非常适合我。计数查询做得很好,计数不是问题。我只是想把这个数组模型转换成主题类的对象。你能解释一下为什么不马上使用
主题类吗?因为它不像我想象的那样工作。