尝试获取非对象 yii 的属性
Trying to get propertyof non-object yii
我开始学习Yii框架,所以我是初学者。我在挣扎。我想使用 yii2 框架从数据库中获取数据。这是我的控制器
public function actionView()
{
$this->view->title = 'List Hotels';
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
return $this->render('index', [
'items' => $items,
]);
}
在我的视图文件中,我使用了如下获取的数据;
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Hotel list';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php foreach ($items as $item): ?>
<p> <?= $item-> name ?></p>
<p> <?= $item->address ?></p>
<p> <?= $item->description ?></p>
<?php endforeach; ?>
当我在 $items 下写 var_dumps($items) 时,我可以看到数据。但是在视图中它说试图获得 属性 'name' 的非对象。我在这里做错了什么请指导我。感谢您的宝贵时间。
$items = Hotel::find()->all();
我不应该添加 Array Helper
ArrayHelper::map()
Returns 一个数组,在您的情况下,传递的第二个参数是一个键,第三个是一个值。因此,您需要将其元素作为数组元素而不是 class 属性来访问。喜欢:
<?php foreach ($items as $key => $value): ?>
<p> <?= $key ?></p>
<p> <?= $value ?></p>
<?php endforeach; ?>
此处有更多详细信息:https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
但是,如果您需要访问数据作为 class 属性,请更改控制器中的行:
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
至:
$items = Hotel::find()->all();
我开始学习Yii框架,所以我是初学者。我在挣扎。我想使用 yii2 框架从数据库中获取数据。这是我的控制器
public function actionView()
{
$this->view->title = 'List Hotels';
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
return $this->render('index', [
'items' => $items,
]);
}
在我的视图文件中,我使用了如下获取的数据;
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
$this->title = 'Hotel list';
$this->params['breadcrumbs'][] = $this->title;
?>
<?php foreach ($items as $item): ?>
<p> <?= $item-> name ?></p>
<p> <?= $item->address ?></p>
<p> <?= $item->description ?></p>
<?php endforeach; ?>
当我在 $items 下写 var_dumps($items) 时,我可以看到数据。但是在视图中它说试图获得 属性 'name' 的非对象。我在这里做错了什么请指导我。感谢您的宝贵时间。
$items = Hotel::find()->all();
我不应该添加 Array Helper
ArrayHelper::map()
Returns 一个数组,在您的情况下,传递的第二个参数是一个键,第三个是一个值。因此,您需要将其元素作为数组元素而不是 class 属性来访问。喜欢:
<?php foreach ($items as $key => $value): ?>
<p> <?= $key ?></p>
<p> <?= $value ?></p>
<?php endforeach; ?>
此处有更多详细信息:https://www.yiiframework.com/doc/api/2.0/yii-helpers-basearrayhelper#map()-detail
但是,如果您需要访问数据作为 class 属性,请更改控制器中的行:
$items = ArrayHelper::map(Hotel::find()->all(), 'id', 'name');
至:
$items = Hotel::find()->all();