Yii框架未知属性异常

时间:2015-02-19 08:51:55

标签: php mysql yii yii2 yii-components

我知道这看起来似乎微不足道,但我真的无法弄明白。我开始使用Yii Framework和MySQL开发数据库应用程序。我试着按照简单的基础教程: http://www.yiiframework.com/doc-2.0/guide-start-databases.html ,但我用自己的桌子"超市"。 我收到此错误:

未知属性 - yii \ base \ UnknownPropertyException 获取未知属性:app \ models \ Supermarkets :: name

很明显,方法获取('名称')导致此错误,但我不知道如何解决此问题。

这是我的代码:

...型号/ supermarkets.php:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Supermarkets extends ActiveRecord
{



}

...控制器/ SupermarketsController.php:

<?php

namespace app\controllers;

use yii\web\Controller;
use yii\data\Pagination;
use app\models\Supermarkets;

class SupermarketsController extends Controller
{
    public function actionIndex()
    {
        $query = Supermarkets::find();

        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);

        $supermarkets = $query->orderBy('name')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('index', [
            'supermarkets' => $supermarkets,
            'pagination' => $pagination,
        ]);
    }
}

...视图/超市/ index.php的:

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<?php foreach ($supermarkets as $supermarket): ?>
    <li>
        <?= $supermarket->name?>
        <?= $supermarket->location ?>
        <?= $supermarket->telephone ?>
        <?= $supermarket->fax ?>
        <?= $supermarket->website ?>
    </li>
<?php endforeach; ?>
</ul>

<?= LinkPager::widget(['pagination' => $pagination]) ?>

Supermarkets.db:

CREATE TABLE IF NOT EXISTS `supermarkets` (
  `Name` varchar(71) NOT NULL,
  `Location` varchar(191) DEFAULT NULL,
  `Telephone` varchar(68) DEFAULT NULL,
  `Fax` varchar(29) DEFAULT NULL,
  `Website` varchar(24) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

你可能会失去模特Supermarkets

/**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'Supermarkets';
    }

如果未设置方法,则默认表名为supermarkets。因为在yii\db\ActiveRecord集合中:

public static function tableName()
    {
        return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
    }

修改

使用从模型中删除此内容

 /**
         * @inheritdoc
         */
        public static function tableName()
        {
            return 'Supermarkets';
        }

并使用

<?= $supermarket->Name?>
        <?= $supermarket->Location ?>
        <?= $supermarket->Telephone ?>
        <?= $supermarket->Fax ?>
        <?= $supermarket->Website ?>

或者更好的方式。使用您的第一个代码。并更改列 - &gt;设置小的第一个字母。像那样

CREATE TABLE IF NOT EXISTS `supermarkets` (
  `name` varchar(71) NOT NULL,
  `location` varchar(191) DEFAULT NULL,
  `telephone` varchar(68) DEFAULT NULL,
  `fax` varchar(29) DEFAULT NULL,
  `website` varchar(24) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;