I would like to ask, if anybody obtained such error before. Since I am stuck for 2 hours fixing bugs with doctrine already. So any kind of of help would be appreciate.
To the point. I am fighting with doctrine Entity Manager I can't make it work.
I created entity and doctrine class to work with, but I am getting an error all the time:
Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class "MSP\Model\Entity\Category" is not a valid entity or mapped super class.' in /home/dariss/www/dom/php/MenuSiteProject/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php:216 Stack trace: #0 /home/dariss/www/dom/php/MenuSiteProject/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php(87): Doctrine\ORM\Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass('MSP\Model\Entit...') #1 /home/dariss/www/dom/php/MenuSiteProject/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php(113): Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass('MSP\Model\Entit...', Object(Doctrine\ORM\Mapping\ClassMetadata)) #2 /home/dariss/www/dom/php/MenuSiteProject/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php(318): Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(Object(Doctrine\ORM\Mapping\ClassMetadata), NULL, false, Array) in /home/dariss/www/dom/php/MenuSiteProject/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php on line 216
My entity class.
namespace MSP\Model\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Category
*
* #ORM\Entity
* #ORM\Table(name="category")
*/
class Category {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="int", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="category_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var String $name
*
* #ORM\Column(name="name", type"string", length=50, nullable=true)
*/
private $name;
/**
* #var integer $parent
*
* #ORM\Column(name="parent", type="int", nullable=true)
*/
private $parent;
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* #return String
*/
public function getName()
{
return $this->name;
}
/**
* #param int $parent
* #return Category
*/
public function setParent($parent)
{
$this->parent = $parent;
return $this;
}
/**
* #return int
*/
public function getParent()
{
return $this->parent;
}
Doctrine class:
namespace MSP\Helper;
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\Common\Cache\ArrayCache,
Doctrine\DBAL\Logging\EchoSQLLogger;
class Doctrine{
public $em = null;
public function __construct()
{
require_once __DIR__.'/../../../vendor/doctrine/common/lib/Doctrine/Common/ClassLoader.php';
$doctrineClassLoader = new ClassLoader('Doctrine', '/');
$doctrineClassLoader->register();
$entitiesClassLoader = new ClassLoader('MSP\Model\Entity', '/../Model/Entity');
$entitiesClassLoader->register();
$proxiesClassLoader = new ClassLoader('Proxies', '/../Proxies/');
$proxiesClassLoader->register();
// Set up caches
$config = new Configuration;
$cache = new ArrayCache;
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver(array('/../Model/Entity'), true);
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
$config->setQueryCacheImpl($cache);
// Proxy configuration
$config->setProxyDir('/proxies');
$config->setProxyNamespace('Proxies');
// Set up logger
$logger = new EchoSQLLogger;
//$config->setSQLLogger($logger);
$config->setAutoGenerateProxyClasses( TRUE );
$iniParser = new \MSP\Helper\IniParser();
$configuration = $iniParser->getConfig();
// Database connection information
$connectionOptions = array(
'driver' => $configuration['driver'],
'user' => $configuration['username'],
'password' => $configuration['password'],
'dbname' => $configuration['dbname'],
'host' => $configuration['host']
);
// Create EntityManager
$this->em = EntityManager::create($connectionOptions, $config);
}
}
Test file:
$doctrine = new MSP\Helper\Doctrine();
$doctrine->em->find('MSP\Model\Entity\Category', 1);
You need to drop the #ORM prefixes when you annotate the entities.
But I followed the example in the Symfony 2 documentation? Yep. For Symfony 2 you need to use #ORM. But your test cases uses "pure" doctrine which means no #ORM.
If you really need to run your stuff using pure doctrine then consider using yaml notation.
Why does S2 use #ORM? It's a long sad story but basically it introduced the #ORM prefix so other annotations would not clash with Doctrine.
Can you tweak the Doctrine configuration to allow the user of #ORM? Yep. But I forget how. You can search for it.
Bottom line: Consider just using the Symfony 2 Doctrine service. It's easier.
You set an absolute path /../Model/Entity.
You need to set ./../Model/Entity
Related
I now a lot of questions already exist about this same error, but all of them are with using YML or Symfony/Zend as framework. I am learning to use Doctrine with my Codeigniter project, and I have gotten upto the point where I generated the Entities using the cli tool:
php cli-doctrine.php orm:convert-mapping --from-database annotation models/entities
And voila, all my entities are generated. Even though I specified in my bootstrap.php I want to use the Entity namespace all the generated classes don't use that namespace. Anyway, I just added that manually. Here is an example of my Entity Vatpercentage in application/models/Entity/Vatpercentage.php:
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Entity\Vatpercentage
*
* #ORM\Table(name="vatpercentage", uniqueConstraints={#ORM\UniqueConstraint(name="id_UNIQUE", columns={"id"}), #ORM\UniqueConstraint(name="code_UNIQUE", columns={"code"}), #ORM\UniqueConstraint(name="vat_UNIQUE", columns={"vat"})})
* #ORM\Entity
*/
class Vatpercentage
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="vat", type="integer", nullable=false)
*/
private $vat = '0';
/**
* #var string
*
* #ORM\Column(name="code", type="string", length=45, nullable=false)
*/
private $code;
/**
* #var integer
*
* #ORM\Column(name="accountnr", type="integer", nullable=true)
*/
private $accountnr;
}
Now I want to call the EntityManager and see if I can retrieve one of my entities from my database. Code in my model:
public function get_vatpercentages(){
$result = $this->doctrine->em->find('Entity\Vatpercentage', 1);
But then I get an Exception:
An uncaught Exception was encountered
Type: Doctrine\ORM\Mapping\MappingException
Message: Class "Entity\Vatpercentage" is not a valid entity or mapped super class.
Filename: /Users/pimdietz/Documents/programming/pos/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/MappingException.php
Line Number: 346
And I cannot figure out why.
For completeness, here is also my bootstrapper in libraries/doctrine.php:
include_once FCPATH . 'vendor/autoload.php';
use Doctrine\Common\ClassLoader;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
class Doctrine {
public $em;
public function __construct() {
// Load the database configuration from CodeIgniter
require APPPATH . 'config/database.php';
$connection_options = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database'],
'charset' => $db['default']['char_set'],
'driverOptions' => array(
'charset' => $db['default']['char_set'],
),
);
// With this configuration, your model files need to be in application/models/Entity
// e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
$models_namespace = 'Entity';
$models_path = APPPATH . 'models';
$proxies_dir = APPPATH . 'models/proxies';
$metadata_paths = array(APPPATH . 'models/Entity');
//Dev mode disables caching methods, otherwise it will try Apc, memcache, etc.:
$dev_mode = ENVIRONMENT == 'development';
// If you want to use a different metadata driver, change createAnnotationMetadataConfiguration
// to createXMLMetadataConfiguration or createYAMLMetadataConfiguration.
$config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode, $proxies_dir);
$this->em = EntityManager::create($connection_options, $config);
$loader = new ClassLoader($models_namespace, $models_path);
$loader->register();
}
}
Please, pretty pretty please, can anyone tell me what I am doing wrong?
Solved it!
I found out I was using the SimpleAnnotationReader, which doesn't like the annotations generated by the orm cli tool command I used:
php cli-doctrine.php orm:convert-mapping --from-database annotation models/entities
As you can see here in the method "createAnnotationMetadataConfiguration" of the Doctrine\ORM\Tools\Setup class the last parameter flags the use of the simpleannotationreader:
/**
* Creates a configuration with an annotation metadata driver.
*
* #param array $paths
* #param boolean $isDevMode
* #param string $proxyDir
* #param Cache $cache
* #param bool $useSimpleAnnotationReader
*
* #return Configuration
*/
public static function createAnnotationMetadataConfiguration(array $paths, $isDevMode = false, $proxyDir = null, Cache $cache = null, $useSimpleAnnotationReader = true)
{
$config = self::createConfiguration($isDevMode, $proxyDir, $cache);
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver($paths, $useSimpleAnnotationReader));
return $config;
}
So in short, All I needed to do to make it work was to give it the false flag for using the simpleannotationreader (in my Doctrine.php bootstrapper):
$config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode, $proxies_dir, null, false);
And now it works fine!
I am building a project management tool for my team in Symfony 3. I am using ramsey/uuid-doctrine for the IDs in the system.
So far, this hasn't been a problem with One-to-Many or Many-to-One associations, but when I try to persist a One-to-One association, Doctrine is not converting the associated entity to its UUID, and instead leaving a null value in the SQL.
In this example, I have a WikiPage which can have multiple WikiPageVersions. The WikiPage has a One-to-Many association with WikiPageVersion (the versions property: for all the versions of the page), but also a One-to-One (Unidirectional) association with WikiPageVersion (the currentVersion property: for the, well, current version).
The WikiPage also has a Many-to-One associations with Project (to track which project the wiki page is for) and that property is populated correctly.
The WikiPage Entity
/**
* #ORM\Table(name="wiki_page")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Project\WikiPageRepository")
*/
class WikiPage
{
/**
* #var Uuid
* #ORM\Id
* #ORM\Column(type="uuid")
*/
protected $id;
/**
* #var Project
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Project\Project", inversedBy="wikiPages")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
protected $project;
/**
* #var string
* #ORM\Column(name="title", type="text")
* #Assert\NotBlank()
*/
protected $title;
/**
* #var HiveWikiPageVersion
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Project\WikiPageVersion", fetch="EAGER")
*/
protected $currentVersion;
/**
* #var ArrayCollection
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Project\WikiPageVersion", mappedBy="wikiPage", cascade={"persist", "remove"})
*/
protected $versions;
// -- Class Methods
}
The WikiPageVersion Entity
/**
* #ORM\Table(name="wiki_page_version")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Project\WikiPageVersionRepository")
*/
class WikiPageVersion
{
/**
* #var Uuid
* #ORM\Id
* #ORM\Column(type="uuid")
*/
protected $id;
/**
* #var WikiPage
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Project\WikiPage", inversedBy="versions")
* #ORM\JoinColumn(name="wiki_page_id", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $wikiPage;
/**
* #var string
* #ORM\Column(name="content", type="text")
* #Assert\NotBlank()
*/
protected $content;
/**
* #var string
* #ORM\Column(name="version_comment", type="string", length=255)
* #Assert\NotNull()
*/
protected $versionComment;
/**
* #var HiveWikiPageVersion
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Project\WikiPageVersion")
* #ORM\JoinColumn(name="previous_version", referencedColumnName="id")
* #Assert\Type(type="Odev\Hive\Model\Entity\Project\WikiPageVersion")
*/
protected $previousVersion;
/**
* #var \DateTimeInterface
* #ORM\Column(name="created", type="datetime")
* #Assert\NotBlank()
*/
protected $created;
/**
* #var User
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumn(name="created_by", referencedColumnName="id")
* #Assert\NotBlank()
*/
protected $createdBy;
}
// -- Methods
Troubleshooting So Far
I can confirm that before persisting the WikiPage, that the WikiPageVersion has been associated.
I can duplicate this same behaviour with my Project and WikiPageVersion entites (Project has a One-to-One association with WikiPage for the wiki homepage and WikiPageVersion has a One-to-One association with itself for the previous version). Only the One-to-One associations are not converting the UUID.
I have the same problem when trying to persist from Symfony Controller or from when loading Doctrine fixtures.
I have tried to trace down where the conversion occurs using xdebug, but I am not that versed in using a debugger and after 20 minutes of stepping through the debugger, I can't find where the conversion for that field happens. I'm either skipping past the loop it happens in or just missing it. After wasting an hour skipping through runs trying to find the problem, I had to give up.
Here is the error I get from Doctrine when I try to perist the WikiPage:
[Doctrine\DBAL\Exception\NotNullConstraintViolationException]
An exception occurred while executing 'INSERT INTO wiki_page (id, project_home, title, project_id, current_version_id) VALUES (?, ?, ?, ?, ?)' with params ["ddc1f51a-f5d9-489f-89bb-cd79f3393af0", 1
, "Technical Reviews Wiki", "5138b185-b10b-48ac-a102-bdea1139c911", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'current_version_id' cannot be null
and the exception trace (this exception is from saving during fixtures loading):
Exception trace:
() at /home/vagrant/hive/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:112
Doctrine\DBAL\Driver\AbstractMySQLDriver->convertException() at /home/vagrant/hive/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:128
Doctrine\DBAL\DBALException::driverExceptionDuringQuery() at /home/vagrant/hive/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:177
Doctrine\DBAL\Statement->execute() at /home/vagrant/hive/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/Entity/BasicEntityPersister.php:281
Doctrine\ORM\Persisters\Entity\BasicEntityPersister->executeInserts() at /home/vagrant/hive/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:1014
Doctrine\ORM\UnitOfWork->executeInserts() at /home/vagrant/hive/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php:378
Doctrine\ORM\UnitOfWork->commit() at /home/vagrant/hive/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:356
Doctrine\ORM\EntityManager->flush() at /home/vagrant/hive/src/Odev/Hive/Infrastructure/AppBundle/DataFixtures/ORM/LoadProjectData.php:89
Odev\Hive\Infrastructure\AppBundle\DataFixtures\ORM\LoadProjectData->load() at /home/vagrant/hive/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php:121
Doctrine\Common\DataFixtures\Executor\AbstractExecutor->load() at /home/vagrant/hive/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/ORMExecutor.php:88
Doctrine\Common\DataFixtures\Executor\ORMExecutor->Doctrine\Common\DataFixtures\Executor\{closure}() at n/a:n/a
call_user_func() at /home/vagrant/hive/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:233
Doctrine\ORM\EntityManager->transactional() at /dev/shm/app/cache/dev/appDevDebugProjectContainer.php:5645
DoctrineORMEntityManager_00000000015ce1f5000000002a2c79364ae5d79093a662a969d1540330e84087->transactional() at /home/vagrant/hive/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/ORMExecutor.php:90
Doctrine\Common\DataFixtures\Executor\ORMExecutor->execute() at /home/vagrant/hive/vendor/doctrine/doctrine-fixtures-bundle/Command/LoadDataFixturesDoctrineCommand.php:118
Doctrine\Bundle\FixturesBundle\Command\LoadDataFixturesDoctrineCommand->execute() at /home/vagrant/hive/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:262
Symfony\Component\Console\Command\Command->run() at /home/vagrant/hive/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:848
Symfony\Component\Console\Application->doRunCommand() at /home/vagrant/hive/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:189
Symfony\Component\Console\Application->doRun() at /home/vagrant/hive/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:80
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /home/vagrant/hive/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:120
Symfony\Component\Console\Application->run() at /home/vagrant/hive/bin/console:29
At this point I am lost - if there is any suggestions of where I should be looking or if anyone else has run into this problem, I would love and guidance that could be provided.
Update
As requested by matteo:
Here is the load method of the fixture that creates the records and throws the error.
/**
* {#inheritDoc}
* #param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
// Create ODEV Project Section
$section = new ProjectSection(
Uuid::uuid4(),
'ODEV',
'ODEV specific projects'
);
$manager->persist($section);
$this->addReference('section-odev', $section);
// Create Technical Review Project -> public
$project = new Project(
Uuid::uuid4(),
'techreview',
$section,
'Technical Reviews',
'Technical Reviews for Work Requests',
false,
false,
$this->getReference('user-system'),
$this->getReference('user-system'),
'',
$this->getReference('user-system')
);
// VarDumper::dump($project->getWikiHome()->getId());
// VarDumper::dump($project->getCreatedBy()->getId());
$manager->persist($project);
$this->addReference('project-tech-review', $project);
$manager->flush();
}
The two VarDumper::dump() commands were to confirm that the associations were getting created.
The actual WikiPage gets generated in the Project's constructor and the WikiPageVersion is generated in the WikiPages's constructor.
Here is Project's constructor:
public function __construct(
string $id,
string $identifier,
ProjectSection $section,
string $name,
string $description,
bool $private,
bool $sensitive,
User $owner,
User $contact,
string $homepage,
User $createdBy
) {
$this->id = Uuid::fromString($id);
$this->identifier = $identifier;
$this->projectSection = $section;
$this->name = $name;
$this->description = $description;
$this->private = $private;
$this->sensitive = $sensitive;
$this->owner = $owner;
$this->contact = $contact;
$this->homepage = $homepage;
$this->createdBy = $createdBy;
$this->created = new \DateTimeImmutable();
$this->updatedBy = $createdBy;
$this->updated = new \DateTimeImmutable();
$this->archived = false;
$this->workRequest = null;
// set up collections
$this->teamMembers = new ArrayCollection();
$this->issues = new ArrayCollection();
$this->folders = new ArrayCollection($this->defaultFolders());
$this->wikiHome = $this->defaultWikiPage();
$this->wikiPages = new ArrayCollection([$this->wikiHome]);
$this->labels = new ArrayCollection($this->defaultLabels());
$this->milestones = new ArrayCollection($this->defaultMilestones());
}
protected function defaultWikiPage(): WikiPage
{
return new WikiPage(Uuid::uuid4(), $this, $this->name.' Wiki', '', $this->createdBy);
}
And the constructor of WikiPage:
public function __construct(string $id, Project $project, string $title, string $content, User $createdBy)
{
$this->id = Uuid::fromString($id);
$this->project = $project;
$this->title = $title;
$this->content = $content;
$this->created = new \DateTimeImmutable();
$this->createdBy = $createdBy;
$this->currentVersion = $this->createFirstVersion($content, $createdBy);
$this->versions = new ArrayCollection([$this->currentVersion]);
}
protected function createFirstVersion(string $content, User $createdBy)
{
return new WikiPageVersion(Uuid::uuid4(), $this, $content, $createdBy, 'Page Created');
}
Hope that helps.
When WikiPage Entity tries to INSERT it is trying to insert all its properties. Do a check for version and if === null unset the key index. then when the
INSERT fires the parm array is only 4 keys.
Before starting, the usual disclaimer : I am aware of dozens of questions here on SE from people encountering identical-looking problems, I have browsed them and unless I missed something, the combination of all the fixes proposed does not solve my particular problem.
In particular :
This question is about duplicated
and inherited entities, which I don't have.
This answer is about
invalid annotation format (missing asterisks), which I don't have in my entity definition (see file content below).
In this question, the problem
comes from a #todo somewhere, which I don't use
In this question, the problem
comes from using eAccelerator which I'm not using at this point
I get the following error message in Symfony :
Doctrine\ORM\Mapping\MappingException: Class "AppBundle\Entity\User" is not a valid entity or mapped super class.
Yet, other commands tell me everything is fine :
$ php bin/console doctrine:mapping:info
Found 6 mapped entities:
[OK] AppBundle\Entity\Category
[OK] AppBundle\Entity\Comment
[OK] AppBundle\Entity\Post
[OK] AppBundle\Entity\Section
[OK] AppBundle\Entity\User
[OK] AppBundle\Entity\World
I also tried
try {
$entityManager->getConnection()->connect();
} catch (\Exception $e) {
echo 'Connection failed !';
}
in my code to see if the connection worked. I also tried "registering noop annotation autoloader" as
suggested in this SO answer
the content of my test file below reflects this ;
<?php
error_reporting(E_ALL|E_STRICT);
require 'app/autoload.php';
xdebug_break();
use AppBundle\Entity;
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\Common\Annotations\AnnotationReader;
use Doctrine\Common\Annotations\AnnotationRegistry;
$paths = array("src/AppBundle/Entity");
$isDevMode = true;
// the connection configuration
$dbParams = array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'root',
'dbname' => 'asharis_database'
);
$config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
$driver = new AnnotationDriver(new AnnotationReader(), $paths);
// registering noop annotation autoloader - allow all annotations by default
AnnotationRegistry::registerLoader('class_exists');
$config->setMetadataDriverImpl($driver);
$entityManager = EntityManager::create($dbParams, $config);
try {
$entityManager->getConnection()->connect();
} catch (\Exception $e) {
echo 'Connection failed !';
}
$users=array();
$post=array();
for($u=1;$u<=3;$u++) {
$user=new AppBundle\Entity\User();
$users[]=$user;
try {
$entityManager->persist($user);
} catch (\Exception $e) {
var_dump($e);
}
And here is the content of User.php :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validation\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*
**/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\OneToMany(
* targetEntity="Comment",
* mappedBy="post",
* orphanRemoval=true
* )
*
*/
private $comments;
/**
* #ORM\OneToMany(
* targetEntity="Post",
* mappedBy="post",
* orphanRemoval=true
* )
*
*/
private $posts;
/**
* Constructor
*/
public function __construct()
{
$this->comments = new \Doctrine\Common\Collections\ArrayCollection();
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add comment
*
* #param \AppBundle\Entity\Comment $comment
*
* #return User
*/
public function addComment(\AppBundle\Entity\Comment $comment)
{
$this->comments[] = $comment;
return $this;
}
/**
* Remove comment
*
* #param \AppBundle\Entity\Comment $comment
*/
public function removeComment(\AppBundle\Entity\Comment $comment)
{
$this->comments->removeElement($comment);
}
/**
* Get comments
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
/**
* Add post
*
* #param \AppBundle\Entity\Posts $post
*
* #return User
*/
public function addPost(\AppBundle\Entity\Posts $post)
{
$this->posts[] = $post;
return $this;
}
/**
* Remove post
*
* #param \AppBundle\Entity\Posts $post
*/
public function removePost(\AppBundle\Entity\Posts $post)
{
$this->posts->removeElement($post);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
Any help appreciated.
"user" is a reserved key word in most database systems.
But that's why you don't see issues when validating your scheme but get issues later on.
I personally had the case that I was able to even create my schema, but when I used DQL I got some issues.
So you have to avoid or handle the "reserved key word". You have two options:
1)
Rename your class or at least give it a different database table name by:
/**
* #ORM\Entity
* #ORM\Table(name="myapp_user")
*
**/
2)
You could also use Doctrine's way to handle reserved keywords (see documentation):
/**
* #ORM\Entity
* #ORM\Table(name="'user'")
*
**/
But I personally don't recommend the second option.
See as well this section about known limitations in Doctrine around your issue here
Small note: I am assuming that you aren't using the FOS User Bundle - in that case your user would need to extend the BaseUser class additionally.
I am making entities using doctrine in codeigniter by reversenginerring (i.e. i had my database and i had made the entities by running the command orm:convert-mapping --form-database annotation models/Entity)
my doctrine.php goes like this ...
<?php
use Doctrine\Common\ClassLoader,
Doctrine\ORM\Tools\Setup,
Doctrine\ORM\EntityManager;
class Doctrine
{
public $em;
public function __construct()
{
require_once __DIR__ . '/Doctrine/ORM/Tools/Setup.php';
Setup::registerAutoloadDirectory(__DIR__);
// Load the database configuration from CodeIgniter
require APPPATH . 'config/database.php';
$connection_options = array(
'driver' => 'pdo_mysql',
'user' => $db['default']['username'],
'password' => $db['default']['password'],
'host' => $db['default']['hostname'],
'dbname' => $db['default']['database'],
'charset' => $db['default']['char_set'],
'driverOptions' => array(
'charset' => $db['default']['char_set'],
),
);
// With this configuration, your model files need to be in application/models/Entity
// e.g. Creating a new Entity\User loads the class from application/models/Entity/User.php
$models_namespace = 'Entity';
$models_path = APPPATH . 'models';
$proxies_dir = APPPATH . 'models/Proxies';
$metadata_paths = array(APPPATH . 'models');
// Set $dev_mode to TRUE to disable caching while you develop
$config = Setup::createAnnotationMetadataConfiguration($metadata_paths, $dev_mode = true, $proxies_dir);
$this->em = EntityManager::create($connection_options, $config);
//changing enum to string coz enum is not support as default by doctrine :)
$platform = $this->em->getConnection()->getDatabasePlatform();
$platform->registerDoctrineTypeMapping('enum', 'string');
$loader = new ClassLoader($models_namespace, $models_path);
$loader->register();
}
}
and the entities which i get after running the commnad goes like this ...
<?php
namespace Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SsClass
*
* #ORM\Table(name="ss_class")
* #ORM\Entity
*/
class SsClass
{
/**
* #var integer $classId
*
* #ORM\Column(name="class_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $classId;
/**
* #var string $class
*
* #ORM\Column(name="class", type="string", length=200, nullable=true)
*/
private $class;
/**
* #var string $classContent
*
* #ORM\Column(name="class_content", type="string", length=500, nullable=true)
*/
private $classContent;
/**
* #var string $isApproved
*
* #ORM\Column(name="is_approved", type="string", nullable=true)
*/
private $isApproved;
/**
* #var string $isActive
*
* #ORM\Column(name="is_active", type="string", nullable=true)
*/
private $isActive;
public function getClassId() {
return $this->classId;
}
public function setClassId($classId) {
$this->classId = $classId;
}
public function getClass() {
return $this->class;
}
public function setClass($class) {
$this->class = $class;
}
public function getClassContent() {
return $this->classContent;
}
public function setClassContent($classContent) {
$this->classContent = $classContent;
}
public function getIsApproved() {
return $this->isApproved;
}
public function setIsApproved($isApproved) {
$this->isApproved = $isApproved;
}
public function getIsActive() {
return $this->isActive;
}
public function setIsActive($isActive) {
$this->isActive = $isActive;
}
}
I am trying to fetch the data from database by my controller name as welcome controller as ..
public function index()
{
//$user=new Entity\SsClass;
$data=$this->em->find('Entity\Ssclass',1);
print_r($data);
//echo $user->get();
die();
}
}
But when i run this code i gote the error as
Fatal error: Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class Entity\Ssclass is not a valid entity or mapped super class.' in D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\MappingException.php:147 Stack trace: #0 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\Driver\AnnotationDriver.php(165): Doctrine\ORM\Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass('Entity\Ssclass') #1 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(293): Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass('Entity\Ssclass', Object(Doctrine\ORM\Mapping\ClassMetadata)) #2 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\ClassMetadataFactory.php(178): Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata('Entity\Ssclass') #3 D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\EntityManager.php(269): Doctrine\ORM\Mapping\ClassMetadataFactory->getMetadataFor( in D:\xampp\htdocs\new_doctrine\application\libraries\Doctrine\ORM\Mapping\MappingException.php on line 147
What is going on here any suggestion??
Have you tried clearing your cache ?
I just ran into the same problem and clearing the cache did it !
You can use the symfony2 command line like so:
$ php app/console cache:clear [--env=yourenv]
Or delete the cache folder in app/cache.
Good luck :)
I am using Doctrine 2 and Zend Framework 1.11. I have set up my Doctrine intergration and it seams to be working in that, I able to get and instance on an Entity Manager to work with. However, I am baffled by the behaviour of the following line in the controller class:
$transfercurrency = $this->entityManager->getRepository('Gesmoney\Entity\Country')->findBy(array('countrycode' => $transfercountry));
When I do a var_dump($transfercurrency), I get an object with a whole bunch of properties, infact, it doesn't look right to me. I tried to post it on pastie but it will not let me because its more than 100kb. I therefore just pasted about a quarter of it enter link description here. Also using Netbeans there seem to be no properties or methods for the returned object hence when I invoke code complete I get nothing. When I do var_dump($transfercurrency[0]->id), I get the following error;
Notice: Undefined property:
Gesmoney\Entity\Country::$property in
/shared/www/dev.gesmoneylatest.com/library/Gesmoney/Entity/Country.php
on line 55 NULL
Its quite a long post but I hope someone has the answer to my problem. Thanks.
Controller class
<?php
class Systemadmin_ExchangerateController extends Zend_Controller_Action
{
/**
* #var Bisna\Application\Container\DoctrineContainer
*/
protected $doctrine;
/**
* #var Doctrine\ORM\EntityManager
*/
protected $entityManager;
public function init()
{
$this->doctrine = Zend_Registry::get('doctrine');
$this->entityManager = $this->doctrine->getEntityManager();
}
public function indexAction()
{
// action body
}
public function getexchangerateAction($transfercountry = 'GB') {
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$transfercurrency = $this->entityManager->getRepository('Gesmoney\Entity \Country')->findBy(array('countrycode' => $transfercountry));
var_dump($transfercurrency);
}
}
Entity
<?php
namespace Gesmoney\Entity;
/**
* #Entity #Table(name="countries")
*/
class Country {
/**
* #Id #Column(type="integer", length=3, nullable=false)
* #GeneratedValue(strategy="IDENTITY")
* #var integer
*
*/
private $id;
/**
* #Column(type="string", length=25)
* #var string
*/
private $countryname;
/**
* #Column(type="datetime")
* #var string
*/
private $lastupdate;
/**
* #Column(type="string", length=2)
* #var string
*/
private $countrycode;
/**
* #Column(type="string", length=20)
* #var string
*/
private $countrycurrency;
/**
* #Column(type="string", length=3)
* #var string
*/
private $currencycode;
/**
* #param \Doctrine\Common\Collections\Collection $property
* #OneToMany(targetEntity="Region", mappedBy="country", cascade={"persist", "remove"})
*/
private $region;
public function __get($property) {
return $this->property;
}
public function __set($property, $value) {
$this->property = $value;
}
}
Application.ini excerpt
;; added for Doctrine2 Integration
pluginPaths.Bisna_Application_Resource = "Bisna/Application/Resource"
; ------------------------------------------------------------------------------
; Doctrine Cache Configuration
; ------------------------------------------------------------------------------
; Points to default cache instance to be used. Optional is only one cache is defined
resources.doctrine.cache.defaultCacheInstance = default
; Cache Instance configuration for "default" cache
resources.doctrine.cache.instances.default.adapterClass = "Doctrine\Common\Cache\ArrayCache"
resources.doctrine.cache.instances.default.namespace = "Application_"
; ------------------------------------------------------------------------------
; Doctrine DBAL Configuration
; ------------------------------------------------------------------------------
; Points to default connection to be used. Optional if only one connection is defined
resources.doctrine.dbal.defaultConnection = default
; Database configuration
;resources.doctrine.dbal.connections.default.parameters.wrapperClass = ""
resources.doctrine.dbal.connections.default.parameters.driver = "pdo_mysql"
resources.doctrine.dbal.connections.default.parameters.dbname = "zzzzz"
resources.doctrine.dbal.connections.default.parameters.host = "localhost"
resources.doctrine.dbal.connections.default.parameters.port = zzzz
resources.doctrine.dbal.connections.default.parameters.user = "root"
resources.doctrine.dbal.connections.default.parameters.password = ""
; ------------------------------------------------------------------------------
; Doctrine ORM Configuration
; ------------------------------------------------------------------------------
; Points to default EntityManager to be used. Optional if only one EntityManager is defined
resources.doctrine.orm.defaultEntityManager = default
; EntityManager configuration for "default" manager
resources.doctrine.orm.entityManagers.default.connection = default
resources.doctrine.orm.entityManagers.default.proxy.autoGenerateClasses = true
resources.doctrine.orm.entityManagers.default.proxy.namespace = "Gesmoney\Entity\Proxy"
resources.doctrine.orm.entityManagers.default.proxy.dir = APPLICATION_PATH "/../library/Gesmoney/Entity/Proxy"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.adapterClass = "Doctrine\ORM\Mapping\Driver\AnnotationDriver"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.mappingNamespace = "Gesmoney\Entity"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.mappingDirs[] = APPLICATION_PATH "/../library/Gesmoney/Entity"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.annotationReaderClass = "Doctrine\Common\Annotations\AnnotationReader"
resources.doctrine.orm.entityManagers.default.metadataDrivers.0.annotationReaderCache = default
You forgot the $ on your properties for __get and __set
public function __get($property) {
return $this->$property;
}
public function __set($property, $value) {
$this->$property = $value;
}