I inherited a zend framework code with doctrine2.
I am trying to add a new column manually to no avail.
1) I create the last_viewed column in db which is dateTime format.
2) I added in the entity file
/**
* #var datetime $lastViewed
*/
protected $last_viewed;
/**
* Set lastViewed
*
* #param datetime $lastViewed
*/
public function setlastViewed($lastViewed) {
$this->last_viewed = $last_viewed;
}
/**
* Get lastViewed
*
* #return datetime
*/
public function gelastViewed() {
return $this->last_viewed;
}
3) Updated the YML file
last_viewed:
type: datetime
But when I try and retrive via
$user->gelastViewed()
I get an empty value.
Also when the entity proxy is generated I don't see the column name in the function "__sleep" rest all other columns are there.
Any suggestions as to how to add this manually.
Turns out cache was the culprit. Restarted Memcache and it works now !!!
Related
Within my database I have two related tables.
AppBooking
AppBookingService
AppBookingService has a foreign key to AppBooking
I use this method to make an insertion in both the first and second table.
public function bookingExecute($data){
try{
$this->em->beginTransaction();
$appBooking = $this->_fillAppBooking($data);
$this->em->persist($appBooking);
if(array_key_exists("appService",$data) && is_array($data['appService']) && count($data['appService']) > 0){
foreach($data['appService'] as $bookingService){
$appBookingService = $this->_fillAppBookingService($bookingService,$appBooking);
$this->em->persist($appBookingService);
$this->em->flush();
}
}
$this->em->flush();
$this->em->commit();
return $appBooking;
}catch (\Exception $ex){
$this->em->rollback();
throw new BookingException("",BookingError::BOOKING_QUERY_ERROR);
}
}
The data is written correctly
After that, in the same http request, I invoke the method below in order to have AppBooking Service data within my entity
$appBooking = $this->bookingService->findOne($id);
The problem that the AppBooking entity I get does not contain AppBookingService
The method
$appBooking->getServices()->count()
returns 0
If I make the same call in another http request I get the desired result.
It is as if doctrine did not update the entity in that same request
This is a part of AppBooking
/**
* #var Collection
* #ORM\OneToMany(targetEntity="AppBookingService", mappedBy="idBooking")
*/
private $services;
public function __construct() {
$this->services = new ArrayCollection();
}
This is part of AppBookingService
/**
* #var \Entity\Entity\AppBooking
*
* #ORM\ManyToOne(targetEntity="Entity\Entity\AppBooking", inversedBy="services")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ID_BOOKING", referencedColumnName="ID_BOOKING", nullable=true)
* })
*/
private $idBooking;
This is because when running
$appBooking = $this->bookingService->findOne($id);
The entity is fetched from his internal proxy cache. No database query is executed to get the entity `s data. The same is true for its already loaded associations. The Proxy cache is valid during the execution of a http request.
To solve this, you either have to update the $services Collection manually or refresh the entity.
$this->em->refresh($appBooking);
Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.
You can also clear the entire entity manager cache before calling the findOne() method.
$this->em->clear();
Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
References
How do I force doctrine to reload the data from the database?
I just fixed some things in my code. I'm now trying to validate my schema
php bin/console doctrine:schema:validate
Doctrine tells me my mapping is correct but my database schema is not. So I'm doing a
schema:update --dump-sql
which results in the same ALTER again and again, that I already performed many times.
Here is the ALTER :
ALTER TABLE migration_versions CHANGE version version VARCHAR(14) NOT NULL;
I did it (with --force), the entity is reflecting the change already :
**
* MigrationVersions
*
* #ORM\Table(name="migration_versions")
* #ORM\Entity
*/
class MigrationVersions
{
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=14, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $version;
I am correct right ? its varchar, lenght 14...
And so is it in my database
I don't think Im making a mistake here but I may be missing something.
Have you already verified that the server_version in the doctrine config file is correct? (config/packages/doctrine.yaml in symfony5)
It happened to me that I was using MariaDB (version 10.4.11-MariaDB - Source distribution) and in the file doctrine.yaml the server_version parameter had the value 5.7.
After I corrected that, the error no longer occurred.
Also you can check this question
Sometimes, I just need to place the value with a config from the end user, just like the database prefix, uploaded File maxSize like below, and etc...
/**
* File
*
* #ORM\Table(name="{projectName}media_file")
* #ORM\Entity(repositoryClass="FileRepository")
* #ORM\HasLifecycleCallbacks()
*/
class File
{
/**
* #var File
*
* #Assert\File(maxSize="{configFromYML}")
*/
protected $file;
What can I do for it? thanks
As far as I know, this is not possible: the configuration parameters are only available in the container.
For the table prefix, maybe you can use the following solution:
How to setup table prefix in symfony2
For the validation, I think the only way to do this is to create a custom validation constraint and to configure it as a service: http://symfony.com/doc/master/validation/custom_constraint.html#constraint-validators-with-dependencies
Hope this will help!
I am new in an project and we want to resume the stand of working still yet.
I found testfiles in project. These were a good point for me to have an entry and find out the things.
So let before say, this is a Symfony 2.8 project which uses fosuserbundle.
Back to my matter: when I execute phpunit in terminal so I get MappingExceptions from doctrine:
PHPUnit 5.1.3 by Sebastian Bergmann and contributors.
WWWWWWWWWWWWWWWWWWWWWWWWWWEWWWWWWEWWWWWWWWWWWWWWWWWWW 53 / 53 (100%)
Time: 1.4 seconds, Memory: 36.50Mb
There were 2 errors:
1) ******\*****Bundle\Tests\Controller\******ControllerTest::testIndex
Doctrine\Common\Persistence\Mapping\MappingException: Invalid mapping file '******.UserBundle.Entity.User.orm.yml' for class '*******\UserBundle\Entity\User'.
/var/www/*****vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/MappingException.php:86
/var/www/********/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/FileDriver.php:117
/var/www/********/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php:56
/var/www/********/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php:102
/var/www/*******/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:116
/var/www/*******/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:332
/var/www/*******/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:216
/var/www/********/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:265
/var/www/********/vendor/doctrine/orm/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php:67
/var/www/********/vendor/doctrine/orm/lib/Doctrine/ORM/Repository/DefaultRepositoryFactory.php:50
/var/www/*******/vendor/doctrine/orm/lib/Doctrine/ORM/EntityManager.php:665
/var/www/*******/vendor/friendsofsymfony/user-bundle/Doctrine/UserManager.php:40
It seems as something going wrong with User entity and related mapping file.
But these errors appear only when I execute phpunit. I deleted the user entity and orm file and run the commands generate entities and update schema. They work without any errors.
Here is the or.yml:
*****\UserBundle\Entity\User:
type: entity
table: fos_user
repositoryClass: ******\UserBundle\Entity\UserRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
confirm:
type: bigint
and here the entity class which extends from fos superclass user
<?php
namespace *****\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
*
*/
class User extends BaseUser
{
/**
* #var integer
*/
protected $confirm;
/**
* Set confirm
*
* #param integer $confirm
* #return User
*/
public function setConfirm($confirm)
{
$this->confirm = $confirm;
return $this;
}
/**
* Get confirm
*
* #return integer
*/
public function getConfirm()
{
return $this->confirm;
}
}
I am spending now the whole day with this issue but I can not figure out what is going wrong. It seems that for doctrine is the yml file invalid but why then it happens only with unittest?
I have a table "cms_objects" // Object.php - that stores all object info
I have another table "cms_media" // Media.php - that stores all media info
An object can have many media items (post with lots of different images)
In Object.php
/**
* #ORM\OneToMany(targetEntity="Media", mappedBy="Object")
*/
private $cms_media;
In Media.php
/**
* #ORM\ManyToOne(targetEntity="Object", inversedBy="cms_media")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*
* #Annotation\Exclude()
*/
private $object;
When I run: php public/index.php orm:validate-schema - I get:
[Mapping] FAIL - The entity-class 'Application\Entity\Cms\Media' mapping is invalid:
* The mappings Application\Entity\Cms\Media#object and Application\Entity\Cms\Object#cms_media are inconsistent with each other.
[Mapping] FAIL - The entity-class 'Application\Entity\Cms\Object' mapping is invalid:
* The association Application\Entity\Cms\Object#cms_media refers to the owning side field Application\Entity\Cms\Media#Object which does not exist.
Ideally, I need to be able to create a ZF2 form with element: 'media' or 'cms_media' but I haven't been able to validate it yet...
You can try to use FQCN inside the annotations. Instead of
/**
* #ORM\OneToMany(targetEntity="Media", mappedBy="Object")
*/
try
/**
* #ORM\OneToMany(targetEntity="Application\Entity\Cms\Media", mappedBy="Object")
*/
in both entities.
Also i would like to recommend using camelCased entity properties instead of underscored_ones. Hydration process of the entities with underscored properties using DoctrineObject hydrator is problematic. You can find more details here.
BEWARE - Using unnecessary bi-directional associations increases your object graph and domain model complexity. Best practice is avoiding bi-directional associations if possible.
For this case, you can rewrite the same mapping using uni-directional relation between Post (Object) and Media entities if you don't need reverse access from Media to Post like
$media->getPost()
For example Application/Entity/Cms/Post.php :
/** #ORM\Entity **/
class Post
{
/**
* One to many, unidirectional
* #ORM\ManyToMany(targetEntity="Application\Entity\Cms\Media")
* #ORM\JoinTable(name="post_to_media",
* joinColumns={#ORM\JoinColumn(name="post_id", referencedColumnName="id")},
* inverseJoinColumns={
* #ORM\JoinColumn(name="media_id", referencedColumnName="id",unique=true)
* })
**/
private $media;
public function __construct()
{
$this->media = new \Doctrine\Common\Collections\ArrayCollection();
}
// ...
}
and Application/Entity/Cms/Media.php :
/** #ORM\Entity **/
class Media
{
// No need to know about post
}