Possible to dynamically change Doctrine Entity mappings? - php

I have a PSR-loaded package that defines a series of relationships around a 'User' entity it provides.
In many of the use cases where you use this package, you may want to keep all entities intact, but, substitute your own User entity.
As concrete example, the package gives me this Entity (using Annotations here to keep things clear):
namespace CirclicalUser\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* An example entity that represents an action rule.
*
* #ORM\Entity
* #ORM\Table(name="acl_actions_users")
*
*/
class UserActionRule
{
/**
* #var int
* #ORM\Id
* #ORM\ManyToOne(targetEntity="CirclicalUser\Entity\ActionRule", inversedBy="user_exceptions")
* #ORM\JoinColumn(name="action_rule_id", referencedColumnName="id")
*/
protected $action_rule;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="CirclicalUser\Entity\User")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
}
Given the above, is there any way I could supplant the user relationship in UserActionRule::$user, that targets CirclicalUser\Entity\User, with my own user: Acme\Entity\User (assuming it is a Doctrine Entity in its own right)
e.g., pretend PHP:
function onBoostrap( $e ){
DoctrineMagic::getMapping(UserActionRule::class)->get('user')->getManyToOne()->setTargetEntity(Acme\Entity\User::class);
}
Thank you!

I managed to solve this by listening to the loadClassMetadata event.
namespace CirclicalUser\Listener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
use Doctrine\Common\EventSubscriber;
class UserEntityListener implements EventSubscriber
{
const DEFAULT_ENTITY = 'CirclicalUser\Entity\User';
private $userEntity;
public function __construct($userEntity)
{
$this->userEntity = $userEntity;
}
public function getSubscribedEvents()
{
return ['loadClassMetadata'];
}
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
/** #var \Doctrine\ORM\Mapping\ClassMetadata $classMetadata */
$classMetadata = $eventArgs->getClassMetadata();
if ($this->userEntity == self::DEFAULT_ENTITY) {
return;
}
switch ($classMetadata->getName()) {
case 'CirclicalUser\Entity\UserActionRule':
$classMetadata->associationMappings['user']['targetEntity'] = $this->userEntity;
break;
}
}
}
This listener successfully substitutes the mapping for the user-defined entity class.
Adding the listener (Zend Framework) was trivial:
'doctrine' => [
'eventmanager' => [
'orm_default' => [
'subscribers' => [
UserEntityListener::class,
],
],
],
Separately, in service manager config:
'service_manager' => [
'invokables' => [
UserAuthenticationLogMapper::class => UserAuthenticationLogMapper::class,
],
'factories' => [
UserEntityListener::class => UserEntityListenerFactory::class,
],
],

Related

Doctrine fails to update schema. "Nothing to update" (Symfony 3.4.8)

I've recently created an Entity with php bin/console doctorine:generate:entity. After creation, I've tried to update my schema with php bin/console doctrine:schema:update --force but got an output of:
Nothing to update - your database is already in sync with the current entity metadata.
Things I've already tried:
php bin/console doctrine:schema:update --dump-sql
Same output
php bin/console doctrine:cache:clear-metadata
Ran, but nothing changed
Clearing cache multiple times
Nothing
php bin/console doctrine:mapping:info
output:
[OK] FOS\UserBundle\Model\Group
[OK] FOS\UserBundle\Model\User
Entity in question:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="WeeklyPaymentReport")
*/
class WeeklyPaymentReport
{
/**
* #var int
*
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(type="integer", nullable=true)
*/
private $bbid;
/**
* #var String
* #ORM\Column(type="string", length=255, nullable=true)
*/
private $request;
/**
* #var \DateTime
*
* #ORM\Column(name="dateOfBirth", type="date", nullable=true)
*/
private $date;
public function getId()
{
return $this->id;
}
public function setBbid($bbid)
{
$this->bbid = $bbid;
return $this;
}
public function getBbid()
{
return $this->bbid;
}
public function setRequest($request)
{
$this->request = $request;
return $this;
}
public function getRequest()
{
return $this->request;
}
public function setDate($date)
{
$this->date = $date;
return $this;
}
public function getDate()
{
return $this->date;
}
}
Doctrine also generated:
namespace AppBundle\Repository;
/**
* WeeklyPaymentReportRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class WeeklyPaymentReportRepository extends \Doctrine\ORM\EntityRepository
{
}
And also .orm.php for it:
use Doctrine\ORM\Mapping\ClassMetadataInfo;
$metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE);
$metadata->customRepositoryClassName = 'AppBundle\Repository\WeeklyPaymentReportRepository';
$metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT);
$metadata->mapField(array(
'fieldName' => 'id',
'type' => 'integer',
'id' => true,
'columnName' => 'id',
));
$metadata->mapField(array(
'columnName' => 'bbid',
'fieldName' => 'bbid',
'type' => 'integer',
));
$metadata->mapField(array(
'columnName' => 'request',
'fieldName' => 'request',
'type' => 'string',
'length' => 255,
));
$metadata->mapField(array(
'columnName' => 'date',
'fieldName' => 'date',
'type' => 'datetime',
));
$metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
What else can I try?
Thank you for your help in advance!
Okay, so right after posting, I've found a post i've never been recommended before which solved the problem.
It's the last sentence, that solved my case.
"After deleting John.orm.php file if i run php bin/console doctrine:schema:update --force then it will generate tables."
Kinda weird solution, I hope I dont encounter weird anomalies in future developments because of it.

Using data of Doctrine Collection from OneToMany association in JSON

I've seen many examples of how to set up a OneToMany association between Entities. However, I have not seen anything on how to output the data from an association. (such as converting to JSON or just having a clean array)
So, here is some sample code:
declare(strict_types=1);
namespace Banks\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/basic-mapping.html
*
* #ORM\Entity
* #ORM\Table(name="bank")
**/
class Banks implements \JsonSerializable
{
/**
* #ORM\Id
* #ORM\Column(type="integer", name="id", nullable=false)
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* A Bank could have Many Branches
*
* #ORM\OneToMany(targetEntity="Branches\Entity\Branches", mappedBy="bank")
*
*/
protected $branches;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $name;
/**
*
* #return array|mixed
*/
public function jsonSerialize()
{
return [
'id' => $this->id,
'name' => $this->name,
'branches' => $this->getBranches()
];
}
public function __construct()
{
$this->branches = new ArrayCollection();
}
public function getBranches(): Collection
{
return $this->branches;
}
// ... Other getter/setters removed
}
Then we also have the Branches Entity:
declare(strict_types=1);
namespace Branches\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/basic-mapping.html
*
* #ORM\Entity
* #ORM\Table(name="branches")
**/
class Branches implements \JsonSerializable
{
/**
* #ORM\Id
* #ORM\Column(type="integer", nullable=false)
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* A Branch has one Bank
*
* #ORM\ManyToOne(targetEntity="Banks\Entity\Banks", inversedBy="branches")
* #ORM\JoinColumn(name="bank_id", referencedColumnName="id")
*/
protected $bank;
/**
* #ORM\Column(type="integer", nullable=false)
*/
protected $bank_id;
/**
* #ORM\Column(type="string", nullable=true)
*/
protected $name;
/**
*
* #return array|mixed
*/
public function jsonSerialize()
{
return [
'id' => $this->id,
'bank_id' => $this->bank_id,
'name' => $this->name,
'bank' => $this->getBank()
];
}
public function getBank()
{
return $this->bank;
}
// ... Other getter/setters removed
}
Querying both Entities work fine overall, with calls to $result->jsonSerialize(), then returning with return new JsonResponse($result) to get a JSON object. Though querying a Branch has the expected result, where I receive the Branch along with the associated Bank as part of the output, the query to Bank is not returning the associated Branches and instead only displays as "branches": {}
I know this is because $branches is a Collection, but how to output it in a way to be part of the resulting JSON object?
I've tried $this->branches->toArray(), but that results in an array of Objects that cannot be encoded to JSON, therefore, ending in an error.
NOTE: The contents (Object) of $this->getBranches() does contain the Branches as expected, which can be seen by $this->branches->count(). But how to reach them in such a way to allow JsonSerializable to create the JSON?
As requested, here is middleware code leaving up to Entity usage:
A factory is used to create what is needed by the Handler:
class BanksViewHandlerFactory
{
public function __invoke(ContainerInterface $container) : BanksViewHandler
{
$entityManager = $container->get(EntityManager::class);
$entityManager->getConfiguration()->addEntityNamespace('Banks', 'Banks\Entity');
$entityRepository = $entityManager->getRepository('Banks:Banks');
return new BanksViewHandler($entityManager, $entityRepository);
}
}
The Factory calls the Handler:
class BanksViewHandler implements RequestHandlerInterface
{
protected $entityManager;
protected $entityRepository;
public function __construct(
EntityManager $entityManager,
EntityRepository $entityRepository,
) {
$this->entityManager = $entityManager;
$this->entityRepository = $entityRepository;
}
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$return = $this->entityRepository->find($request->getAttribute('id'));
$result['Result']['Banks'] = $return->jsonSerialize();
return new JsonResponse($result);
}
}
The handler returns the JSON.
It's important to note that, when implementing the \JsonSerializable interface, calling jsonSerialize() directly does not return JSON, and you do not call this method explicitly.
As stated in the docs:
Objects implementing JsonSerializable can customize their JSON representation when encoded with json_encode().
The intent of implementing this interface is to enforce the jsonSerialize() method, which is called internally when passing the object(s) to json_encode(); e.g:
$result = $banksRepository->find($id);
$json = json_encode($result);
Additionally, if you want to serialize the child Branch entities as well you need to:
Implement \JsonSerializable for this entity (which you have done)
Doctrine will return these Branches as an ArrayCollection object, containing all child Branch objects. In order to ensure that json_encode() encodes these to JSON properly you need to convert the ArrayCollection to an array using toArray().
To illustrate - (as you pointed out you also implemented this):
public function jsonSerialize()
{
return [
'id' => $this->id,
'name' => $this->name,
'branches' => $this->getBranches()->toArray(), // <--
];
}
This should serialise your Bank and associated Branch entities as expected. Hope this helps :)

Symfony 4 + Doctrine: organize entities in subfolders

I'm trying to make a website with Symfony 4 and Doctrine. I'm a complete beginner (both with Symfony and PHP in general), so I apologise if my question is trivial.
I want to create a database with doctrine, which means that I have to create classes in src/Entity. But I also want to add forms to the site, and they also require classes in src/Entity. I'd like to separate these classes in two subfolders: src/Entity/database and src/Entity/forms. I tried to edit config/packages/doctrine.yaml as follows:
doctrine:
#...
orm:
#...
mappings:
App:
#...
dir: '%kernel.project_dir%/src/Entity/database'
prefix: 'App\Entity\database'
But I when I use bin/console make:entity Entity it creates the file in src/Entity and gives the following error:
[ERROR] Only annotation mapping is supported by make:entity, but the
<info>App\Entity\Entity</info> class uses a different format. If you
would like this command to generate the properties & getter/setter
methods, add your mapping configuration, and then re-run this command
with the <info>--regenerate</info> flag.
When I run bin/console make:entity Entity --regenerate it says:
[ERROR] No entities were found in the "Entity" namespace.
I also tried bin/console make:entity database/Entity, but it fails with:
[ERROR] "App\Entity\Database/Entity" is not valid as a PHP class name (it must start with a letter or underscore,
followed by any number of letters, numbers, or underscores)
If I do the same with a backslash (database\Entity) it creates a DatabaseEntity.php file in the wrong directory and gives the same error as the first one.
Be very careful, because with such approach you might mess your architecture up. This question is a bit opinionated, but I'm gonna tell you how we make it with entities and forms.
First, my strong belief, Entities and Forms should be separated. Therefore, we contain Entites in src/Entity and Forms in src/Form. The connection between them is a FormType, we contain those in src/FormType.
Here's an example User entity contained in src/Entity/User.php:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #UniqueEntity("username")
*
* #ORM\Entity()
* #ORM\Table(name="users")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #var int
*/
private $id;
/**
* #Assert\NotBlank()
* #Assert\Email
* #Assert\Length(max="255")
*
* #ORM\Column(type="string", length=255, unique=true)
*
* #var string
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*
* #var string
*/
private $password;
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #return string The username
*/
public function getUsername()
{
return $this->username;
}
/**
* #param null|string $username
*
* #return User
*/
public function setUsername(?string $username): User
{
$this->username = (string) $username;
return $this;
}
/**
* #return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* #param null|string $password
*
* #return User
*/
public function setPassword(?string $password): User
{
$this->password = (string) $password;
return $this;
}
}
Now, we need a user to be able to register. For this we create a FormType and a Form. Take a look at src/FormType/User.php:
namespace App\FormType;
use App\Entity;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as NativeType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
class User extends AbstractType
{
public function getParent(): string
{
return BaseType::class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
// This maps `Entity\User::username` to the respective field
$builder->add(
'username',
NativeType\EmailType::class,
['label' => 'username']
);
// This maps `Entity\User::password` to the respective field
$builder->add(
'password',
NativeType\RepeatedType::class,
[
'constraints' => [new NotBlank()],
'invalid_message' => 'nonMatchingPasswords',
'first_options' => ['label' => 'password'],
'second_options' => ['label' => 'password again'],
'type' => NativeType\PasswordType::class,
]
);
}
// This tells Symfony to resolve the form to the `Entity\User` class
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(['data_class' => Entity\User::class]);
}
}
And now the Form itself, it's src/Form/UserRegistration.php:
namespace App\Form;
use App\FormType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type as NativeType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints;
class UserRegistration extends AbstractType
{
public function getParent()
{
// Note this!
return FormType\User::class;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'fields' => ['username', 'password'],
'translation_domain' => 'forms',
]
);
}
}
And a final stroke on this. In src/Controller/Registration.php we do this:
$form = $this->createForm(
Form\UserRegistration::class,
$user = new Entity\User()
);
The rest (how to handle forms etc.) you know. If you don't, read Symfony docs, they cover it perfectly.
I have cut out / edited some sensitive or non-essential things from this example. For instance, we do not bind password to password, we ask for plain password and then encrypt it. I have not tested the above, so it might not be stable. But for a demonstration on how your architecture should be done it's a good example, IMO.

Symfony2 Doctrine2 UniqueEntity on ManyToOne field is ignored

I have a OneToMany relationship between Project and Application, and I want to be sure that 2 Applications cannot have the same name inside a Project.
I tried to configure my entity, form type and controller like it should be, but I am getting an Integrity contraint violation for duplicated entry, so I think the validation process is ignored.
Can someone tell me what am I missing ?
My Application entity like this :
namespace App\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use JsonSerializable;
/**
* #ORM\Entity
* #ORM\Table(name="application", uniqueConstraints={#ORM\UniqueConstraint(name="IDX_Unique", columns={"name", "project_id"})})
* #UniqueEntity(
* fields={"name", "project"},
* message="Name already used in this project.",
* groups="application"
* )
*/
class Application implements JsonSerializable {
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string")
* #Assert\NotBlank(
* message = "Name cannot be empty."
* )
* #Assert\Length(
* min = "3",
* max = "50",
* minMessage = "Name is too short. It should have {{ limit }} characters or more.",
* maxMessage = "Name is too long. It should have {{ limit }} characters or less."
* )
*/
protected $name;
// other properties ...
/**
* #ORM\ManyToOne(targetEntity="Project", inversedBy="applications")
* #ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
protected $project;
// constructor, methods, getters, setters
}
My ApplicationType class looks like this :
namespace App\MainBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ApplicationType extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('name', 'text', array(
'icon' => 'pencil'
));
$builder->add('description', 'textarea', array(
'required' => false,
'icon' => 'info'
));
$builder->add('url', 'url', array(
'required' => false,
'icon' => 'link'
));
}
public function getName() {
return 'application';
}
public function setDefaultOptions(OptionsResolverInterface $resolver) {
$resolver->setDefaults(array(
'data_class' => 'App\MainBundle\Entity\Application',
'validation_group' => array('application'),
'cascade_validation' => true
));
}
}
And in my Controller the action looks like this:
/**
* #Route("/project/{id}/application/add",
* name="app_add_application_ajax",
* requirements={"_method" = "post"},
* options={"expose" = true }
* )
* #Secure(roles="ROLE_SUPER_ADMIN")
* #ParamConverter("project", class="AppMainBundle:Project")
*/
public function addApplicationAction(Project $project, Request $request) {
$ajaxResponse = array();
$em = $this->getDoctrine()->getManager();
if ($request->getMethod() == 'POST' && $request->isXmlHttpRequest()) {
$formApp = new Application();
$formApp->setProject($project);
$form = $this->createForm(new ApplicationType(), $formApp);
$form->handleRequest($request);
if ($form->isValid()) {
$application = $form->getData();
$em->persist($application);
$em->flush();
// build ajax response ...
} else {
$ajaxResponse['error'] = $this->getErrorsAsString();
}
}
$response = new Response(json_encode($ajaxResponse));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
Your issue is that you configure a validation_group option in your form type, while the option used by Symfony is validation_groups. You don't get an error about an unknown option because you are setting this in the default options of your form type, and so you are marking the option as defined (but it is a separate one).
So the validator runs with the default group, which will validate different constraints (the constraints on the length of the name property are in the default group).
Note that you also have a second issue, which would appear once you run the constraint.
Your validation constraint does not match the DB constraints you have. You are asking the validator to have a unique name and a unique project, not a unique tuple (name, project). So you would reject too much things (the name will be validated as unique globally, not per project).
This is because you use 2 separate UniqueEntity constraints instead of a constraint asking for a tuple of multiple fields to be unique.

ZF2: The target-entity cannot be found in 'Application\Entity\ #user'

I'm using Zend Framework 2 with Doctrine2.
I use a User and Project entity. A user can have more projects and a project can have multiple users. So i use another entity User_Project.
They are all set up and I've validated the schema. All mapping files are correct and the database schema is in sync (orm:validate-schema).
When I try to get all my users, I get an error that the target entity cannot be found (see title). Same error when I try getting one user.
ERROR
The target-entity Application\Entity\User_Project cannot be found in 'Application\Entity\User#user'.
Controller:
return $this->getEntityManager()->getRepository('Application\Entity\User')->findAll();
User entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
* #ORM\Table(name="user")
**/
class User {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="user_id")
*/
protected $user_id;
/** #ORM\Column(type="string") */
protected $fullName;
/** #ORM\OneToMany(targetEntity="User_Project", mappedBy="user") */
protected $user;
public function getUserId()
{
return $this->user_id;
}
public function getFullName()
{
return $this->fullName;
}
public function setFullName($value)
{
$this->fullName = $value;
}
}
Project entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
#ORM\Table(name="project")
**/
class Project {
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer", name="project_id")
*/
protected $project_id;
/** #ORM\Column(type="string") */
protected $customer;
/** #ORM\Column(type="string") */
protected $project_name;
/** #ORM\OneToMany(targetEntity="User_Project", mappedBy="project") */
private $project;
public function getProjectId()
{
return $this->project_id;
}
}
User_Project entity
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/** #ORM\Entity
* #ORM\Table(name="user_project")
**/
class User_Project {
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="User", inversedBy="user")
* #ORM\JoinColumn(name="user_id", referencedColumnName="user_id", nullable=false)
*/
protected $user;
/**
* #ORM\Id()
* #ORM\ManyToOne(targetEntity="Project", inversedBy="project")
* #ORM\JoinColumn(name="project_id", referencedColumnName="project_id", nullable=false)
*/
protected $project;
public function getUser()
{
return $this->project;
}
public function getProject()
{
return $this->user;
}
public function setUser($value)
{
$this->user = $value;
}
public function setProject($value)
{
$this->project = $value;
}
}
Modules.php
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function onBootstrap(MvcEvent $e)
{
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
}
may definition of your entity in Module.php or module.config.php is wrong .
please copy Module.php or module.config.php
correct definition in module.config.php:
return array(
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity')
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
))))),
in user Entity may be better rename user property to userProjects or projects and apply change on relation definition on User_Project
check your column names in database . if you want have correct db . i recommend schema tool for create db .
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->getEntityManager());
$classes = array(
$this->getEntityManager()->getClassMetadata('Application\Entity\User'),
$this->getEntityManager()->getClassMetadata('Application\Entity\Project'),
$this->getEntityManager()->getClassMetadata('Application\Entity\User_Project'),
);
$tool->dropSchema($classes);
$tool->createSchema($classes);
in a controller or somewhere else .

Categories