如何解决类xxx不是有效实体或映射超类错误

时间:2013-02-13 10:22:48

标签: php orm doctrine-orm entity

我已经定义了这样的类设置:

<?php

use Doctrine\ORM\Mapping as ORM;

/** @ORM\Entity */
class Setting {
    /** @ORM\Column(type="integer")
     *  @ORM\GeneratedValue
     *  @ORM\id
     */
    private $id;

    /** @ORM\Column(length=255, nullable=true) */
    private $displayname;

    /** @ORM\Column(length=255) */
    private $name;

    /** @ORM\Column(type="text") */
    private $value;

    public function __get($name) {
        return $this->$name;
    }

    public function __set($key, $value){
        $this->$key = $value;
    }

    public function getFullName() {
        return $this->name . ' suffix';
    }


    public static function getValue($settingName) {
        $result = '';
        try {
            $setting = em()->createQuery('SELECT s FROM Setting s WHERE s.name = :name')
                ->setParameter('name', $settingName)
                ->getSingleResult();

            $result = $setting->value;
        }
        catch (\Doctrine\ORM\NoResultException $exception) {

        }

        return $result;
    }
}

不幸的是,这会产生错误致命错误:Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class "Setting" is not a valid entity or mapped super class.' in xxxxx/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php on line 216

如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

要解决此问题,我必须在最后一个参数中使用false调用Setup::createAnnotationMetadataConfiguration以避免使用SimpleAnnotationReader,因为您需要AnnotationReader来使用ORM \名称空间前缀。

use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;

$dbParams = array(
    'driver' => 'pdo_mysql',
    'host' => '127.0.0.1',
    'user' => 'root',
    'password' => '', 
    'dbname' => 'db',
);

$path = __DIR__ . '/Entity';

$config = Setup::createAnnotationMetadataConfiguration(array($path), true, null, null, false);

$entityManager = EntityManager::create($dbParams, $config);

答案 1 :(得分:1)

找到解决方案:似乎问题在于使用SimpleAnnotationReader。

当像这样配置annotationDriver时(第二个参数应该为false),它可以工作。

$driver = $config->newDefaultAnnotationDriver(
    APPLICATION_PATH . '/models', false
);