I am having a [Doctrine\ORM\ORMException] Unknown Entity namespace alias 'src\AppBundle\Entity'
error message.
A quick search led me to three related SO questions :
here about
a problem in a user-created bundle, which I'm not using here.
here where
the error message is obtained by PHP code rather using doctrine in the command line as I'm currently doing, and
there where the answer suggests doing sudo php app/console cache:clear --env=dev ; I did that followed by sudo chmod a+w app/cache/dev/annotations, but the problem stayed the same.
Here is what I did :
1) Successfully create my database with php app/console doctrine:database:create
2) Create manually a Product Entity in app/Entity/Product.php with the following content (the code below is
copy-pasted from the Symfony Book) :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="decimal", scale=2)
*/
protected $price;
/**
* #ORM\Column(type="text")
*/
protected $description;
}
3) Type php app/console doctrine:generate:entities src/AppBundle/Entity:Product - which produced the "unknown entity namespace" error message.
Any help appreciated.
There are two syntaxes that are/will be used throughout your Symfony2 app.
\My\Company\Namespace\Entity\Product
MyCompanyNamespace:Product
I believe that putting a src anywhere in your code/config would be in violation with PSR-0. Symfony2 does a very good job of seeing everything thought a bundle. That is why you have to have at least one in your app - everything it a bundle
Related
The original problem
The reasons, notes and members fields bellow where #ORM\Column(type="string", length=20000) which did not work because that is too long for a VARCHAR so I changed them all to #ORM\Column(type="text")
And Now
It is possible that I have misunderstood the correct way to handle migrations in productions but I can't get my database to match my entity. Running php bin/console doctrine:migrations:diff or php bin/console doctrine:schema:update --dump-sql doctrine tries to update the database to an old version of Request.php like it has been cached but even after running clear-metadata the migrations all say VARCHAR(20000) like in this sql dump after I manually changed the database:
ALTER TABLE request CHANGE reasons reasons VARCHAR(20000) NOT NULL, CHANGE notes notes VARCHAR(20000) DEFAULT NULL, CHANGE members members VARCHAR(20000) NOT NULL;
Current Request.php
namespace App\Entity;
use App\Repository\RequestRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity(repositoryClass=RequestRepository::class)
*/
class Request
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="time")
* #Assert\LessThan(propertyPath="endTime", message="The booking must start before it ends")
*/
private $startTime;
/**
* #ORM\Column(type="time")
*/
private $endTime;
/**
* #ORM\Column(type="date")
*/
private $date;
/**
* #ORM\Column(type="text")
*/
private $reasons;
/**
* #ORM\Column(type="text", nullable=true)
*/
private $notes;
/**
* #ORM\Column(type="text")
*/
private $status;
/**
* #ORM\ManyToOne(targetEntity=User::class, inversedBy="requests")
* #ORM\JoinColumn(nullable=true)
*/
private $user;
/**
* #ORM\Column(type="text")
*/
private $members;
I have tried removing the Request.php entity but then doctrine gets upset that it is gone. (I do have a relational link to the user table here but it is one to many).
Changing the names of members reasons and notes worked but when I changed the names back it wanted to set them back to VARCHAR(20000). Where is it holding this info. How do I get rid of it?
Doctrine Metadata is cached. When you clear the cache (and warming it back up), symfony runs "compiler passes" that among other things read annotations to build the metadata, proxy objects, registers repositories, all this kind of stuff (obviously other doctrine-unrelated stuff as well).
Running bin/console cache:clear should solve your problems. (It also should be part of your deployment process. And unless you copy over the vendor dir as well, composer install too).
I'm working to fix some bugs and add new features to a project already in production.
What I need to do I think is very simple for who knows Symfony2 and Doctrine but I'm newbie and I don't know how to achive what i need:
I've got an existing entity on PHP side that is associated with a table in the database.
What I need is to create another entity that has some foreign key with other table.
I've tried to create the table into database first, but I don't know how to create the associated entity in PHP ( with correct annotation pointing to the foreign keys) and how to edit the other entities that need new attribute in class.
What I've also tried is to create an annotated PHP class as this:
<?php
namespace MyProject\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Groups;
use JMS\Serializer\Annotation\SerializedName;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\VirtualProperty;
use MyProject\MyBundle\Model\ItemThumb;
/**
* #ORM\Entity
* #ORM\Table(name="wall_message_comment_answer")
*/
class WallMessageCommentAnswer {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #Groups({"user_details", "search_around"})
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="wall_message_comments")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
* #Groups({})
*/
public $user;
/**
* #var WallMessage
* #ORM\ManyToOne(targetEntity="WallMessage", inversedBy="users_comments")
* #ORM\JoinColumn(name="wall_message_id", referencedColumnName="id", onDelete="CASCADE")
*/
public $wall_message;
/**
* #var WallMessage
* #ORM\OneToMany(targetEntity="WallMessageComment", mappedBy="comment_answers")
* #ORM\JoinColumn(name="wall_message_comment_id", referencedColumnName="id", onDelete="CASCADE")
*/
public $wall_message_comment;
/**
* #var string
* #ORM\Column(type="string")
* #Groups({"user_details", "search_around"})
*/
public $content;
/**
* #var int
* #ORM\Column(type="integer")
* #Groups({"user_details", "search_around"})
*/
public $timestamp;
}
and then, trying to create getter and setter, launch the command:
php app/console doctrine:generate:entities MyProjectMyBundle/Entity/WallMessageCommentAnswer
But it gives me that error:
[Symfony\Component\Debug\Exception\FatalErrorException]
Compile Error: Cannot redeclare MyProject\MyBundle\Entity\User::setDocumentNumber()
as it tries to create again other entities.
Could anyone help me?
Thanks!
Why don't you try creating Entity using php app/console doctrine:generate:entity command. This will ask you for Bundle name, Entity name and columns.
After this you'll have .php file created in specified bundle. Following this URL to manually add relationship between your current and new entity.
http://symfony.com/doc/current/book/doctrine.html#relationship-mapping-metadata
This is how you can give manyToOne relationship in Symfony usng annotations, you can switch your way to assigning this relationship. (YML or any other supported by Symfony)
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
And specify oneToMany in target entity like this
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
After you're done with this run the following command to get the SQL queries of the changes.
php pap/console doctrine:schema:update --dump-sql
You'll have SQL queries output which you need to copy and run on the production environment. If your production and testing environment are same run following command.
php pap/console doctrine:schema:update --force
For above procedure you don't have the table to be created in database. Doctrine does that for you.
If you already have table created you can remove that as it's going to be created automatically when you force the schema.
I have an existing ZF2 project to which I have added entities before, and I have just added a new entity by copying an existing one and changing the details as necessary. This UserCmsPermission entity links to the User entity via the User entity's cmsPermissions property.
I have redeployed the database using the following commands:
doctrine-module orm:schema-tool:drop --force
doctrine-module orm:schema-tool:create
doctrine-module data-fixture:import
This executes successfully with no errors at all. However, when I access my application I receive the following error:
The target-entity Application\\Entity\\UserCmsPermission cannot be found in
'Application\\Entity\\User#cmsPermissions'.
The relevant code from each entity is as follows:
module/Application/src/Application/Entity/User.php
<?php
/**
* User model
*
*
*/
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Tilt\Entity\Base\User as TiltUser;
/**
* #ORM\Entity
*/
class User extends TiltUser
{
// … etc …
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="UserChallenge", mappedBy="user", cascade={"all"})
*/
protected $challenges;
/**
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="UserCmsPermission", mappedBy="user", cascade={"all"})
*/
protected $cmsPermissions;
// … etc …
}
module/Application/src/Application/Entity/UserCmsPermission.php
<?php
/**
* User CMS Permission model
*
*
*/
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Tilt\Exception\InvalidArgumentException;
use Tilt\Entity\Base\Entity as BaseEntity;
/**
* #ORM\Entity
*/
class UserCmsPermission extends BaseEntity
{
// … etc …
/**
* #var User
*
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
* #ORM\ManyToOne(targetEntity="User", inversedBy="cmsPermissions", cascade={"all"})
*/
protected $user;
// … etc …
}
As far as I can tell, the code is correct, and I have also removed data/DoctrineORMModule/ in case the entity metadata was being cached, but this hasn't fixed the problem, and neither has restarting PHP5-FPM in case something was being cached there, so I've now run out of ideas.
Anyone got a clue as to what could be causing this to happen?
Finally figured out what is causing this. Doctrine throws this error if you are using a class map to load classes rather than the standard ZF2 autoloader and you've forgotten to update your class map, which was what I'd not done.
Simply running this in the project folder fixed it:
php vendor/zendframework/zendframework/bin/classmap_generator.php
Et voila.
As I am creating a web application that will be used in research on patients in the health domain, I want all my users to be completely anonymous. Can I in a simple way get rid of the email and email_canonical fields without rewriting stuff in the bundle itself, for instance by doing something to my User Class in my own bundle?
EDIT: I did this:
/**
* #ORM\Column(nullable=true)
**/
protected $email;
/**
* #ORM\Column(nullable=true)
**/
protected $emailCanonical;
In my User entity class. Bu twhen I do php app/console doctrine:schema:update --force i get
[Doctrine\ORM\Mapping\MappingException]
Duplicate definition of column 'email' on entity 'Pan100\MoodLogBundle\Enti
ty\User' in a field or discriminator column mapping.
EDIT 2: Forgot to say this is done in a class extending the FOUserBundle's model class User as BaseUser...
OK!
I did:
...
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #ORM\AttributeOverrides({
* #ORM\AttributeOverride(name="email", column=#ORM\Column(nullable=true)),
* #ORM\AttributeOverride(name="emailCanonical", column=#ORM\Column(nullable=true, unique=false))
*
* })
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...(code emitted)
Later I will find out if more is needed - I will probably have to override some of the FOSUserBundle methods for creating users. At least the "php app/console fos:user:create testuser" command requires an email... But it does not have to be unique anymore, so if I am hindered later I can just add the string "none" or something...
i'm trying to install the "gedmo" behaviourial extensions (version 2.1.0-DEV) in Doctrine2 (version 2.1.3).
Without the extensions everything works fine. However, when I add the annotationdriver to read the #gedmo-annotations errors such as "Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class User2 is not a valid entity or mapped super class" are thrown.
This is de User2-entity:
<?php
use \Doctrine\ORM\Mapping as ORM;
/** #ORM\Entity */
class User2 {
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/** #ORM\Column(length=255) */
private $username;
}
Because these errors occur even in the Entities where #gemdo is not used i suspect it has something to do with the way the annotationdrivers are configured. In my bootstrap-file the annotation driver is added (i'm only going to use the tree-extension):
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader);
$chain = new \Doctrine\ORM\Mapping\Driver\DriverChain;
$chain->addDriver($annotationDriver, 'Gedmo\Tree\Entity');
$config->setMetadataDriverImpl($chain);
A few questions:
Should I add a driver for the ORM-annotation?
Is there something wrong with the User2-class?
How can I get a more specific user-error enabling me to find the exact cause of the problem?
In short: how can I make the #orm and #gedmo annotations work?
there was recently an example added in order to show how to configure bare entity manager with extensions whithout any framework used.
You can follow the readme at the bottom on how to setup it initially