I'm new to PHP and also with Doctrine. (Worked before with Hibernate ORM implementation).
My problem is that after I fetch a record from my database by the entityManager, I can't access the object methods at all. Below are some code snippets:
Entity manager creation:
$classLoader = new \Doctrine\Common\ClassLoader('entities');
$classLoader->register();
$config = new Configuration();
$cache = new ArrayCache();
$config->setMetadataCacheImpl($cache);
$driverImpl = $config->newDefaultAnnotationDriver('entities');
$driverImpl->getAllClassNames();
$config->setMetadataDriverImpl($driverImpl);
$config->setQueryCacheImpl($cache);
$config->setProxyDir('proxies');
$config->setProxyNamespace('proxies\namespaces');
$config->setAutoGenerateProxyClasses(true);
$em = EntityManager::create(getConnOptions(), $config);
it works fine!
Here is my Entity class :
namespace entities\positions;
/**
* Positions
*
* #Table(name="positions")
* #Entity
*/
class Positions
{
/**
* #var bigint $id
*
* #Column(name="id", type="bigint", nullable=false)
* #Id
* #GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $notes
*
* #Column(name="notes", type="string", length=255, nullable=true)
*/
private $notes;
/**
* #var integer $number
*
* #Column(name="number", type="integer", nullable=true)
*/
public $number;
/**
* #var Volumes
*
* #ManyToOne(targetEntity="Volumes")
* #JoinColumns({
* #JoinColumn(name="volume_id", referencedColumnName="id")
* })
*/
private $volume;
public function getNumber() {
return $this->number;
}
}
and here is the code that generates error:
$found = $this->em->find('Positions', 1);
echo $found->getNumber();
the error that I get is the following:
Fatal error: Call to undefined method Positions::getNumber() in /var/www/php-test/business/Test.php on line 30
Can you suggest me how to fix it?
Thanks.
N.B. It gives me the same error if I try to call : $found->number, that I have made public for this reason.
The problem is due to the fact that I was declared the namespace in entities. This was the reason for what I got this error. If you have entities under entities/ directory scattered in it's own directory, you need to put this paths in the driver creation array configuration :
$driverImpl = $config->newDefaultAnnotationDriver(array("entities", "entities/dir1", "entities/dir2"));
That does the trick.
Related
i've just got this error
Case mismatch between loaded and declared class names: MyApp\UserBundle\Entity\post vs MyApp\UserBundle\Entity\Post
i'm using two controllers to do a specific operation of delete and getting back to the old page
here is my button's code
<a href="{{ path('DeleteComment',{'idc':comment.id}) }}"> <i
class="icon-trash"></i>Delete</a>
here is my routing's code :
get_view_post:
path: /blog/get/one/post/{id}/
defaults: { _controller: "MyAppBlogBundle:Blog:getpost" }
DeleteComment:
path: /blog/post/comment/delete/{idc}/
defaults: { _controller: "MyAppBlogBundle:Blog:DeleteComment" }
here is my controllers code :
public function DeleteCommentAction($idc)
{
$em = $this->getDoctrine()->getManager();
$comment = $em->getRepository('MyAppUserBundle:PostComment')->find($idc);
$idPost =$comment->getIdPost();
$em->remove($comment);
$em->flush();
return $this->redirectToRoute("get_view_post", array('id' => $idPost));
}
public function getpostAction($id)
{
$user = $this->getUser();
$idu = $user->getId();
$em = $this->getDoctrine()->getManager();
$em1 = $this->getDoctrine()->getManager();
$post = $em->getRepository('MyAppUserBundle:Post')->find($id);
$idPost=$post->getId();
$comment = $em1->getRepository('MyAppUserBundle:PostComment')->findBy(array('idPost' => $idPost));
return $this->render('MyAppBlogBundle::afficherPostAvecComment.html.twig', array('posts' => $post,'comments'=>$comment,'idu'=>$idu));
}
i'm declaring my entities like this :
use MyApp\UserBundle\Entity\Post;
use MyApp\UserBundle\Entity\PostComment;
Here is my Entity
namespace MyApp\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="post")
*/
class Post
{
/**
* #var integer
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
* #ORM\Column(name="titre", type="string", length=100, nullable=false)
*/
private $titre;
/**
* #var string
* #ORM\Column(name="contenu", type="string", length=250, nullable=false)
*/
private $contenu;
/**
* #var \DateTime
* #ORM\Column(name="dateajout", type="datetime", nullable=true)
*/
private $dateajout ;
/**
* #var integer
* #ORM\ManyToOne(targetEntity="User")
* #ORM\JoinColumn(name="id_utilisateur",referencedColumnName="id")
*/
private $idUser;
/**
* #var integer
* #ORM\Column(name="nbLike", type="integer", nullable=true)
*/
private $nbLike =0;
/**
* #var integer
* #ORM\Column(name="nbDislike", type="integer", nullable=true)
*/
private $nbDislike=0;
/**
* #var integer
* #ORM\Column(name="nbSignal", type="integer", nullable=true)
*/
private $nbSignal=0;
i did some changes in my code, as i see My IDE couldn't differentiate
between Post, PostComment and my array post or furthermore his own method of recuperation _POST.
you can see from the error above that it's based on hesitation between Post and post ,if you are using a latest version of Symfony, try to scan you whole project and change the names of your attributes or classes, believe it or not it creates some difficulties for the IDE when your project gets bigger
and here is what made the error gone:
old
/**
* #var integer
* #ORM\ManyToOne(targetEntity="post")
* #ORM\JoinColumn(name="id_post",referencedColumnName="id")
*/
private $idPost;
new
/**
* #var integer
* #ORM\ManyToOne(targetEntity="Post")
* #ORM\JoinColumn(name="id_post",referencedColumnName="id")
*/
private $idPost;
I was not giving the appropriate name of my Entity, so when I do any operation based on foreign keys, the IDE won't find any Entity of reference
if you are using and old version of Symfony, you have to add a line of code in some file's configuration
you can have a better explanation here:
Symfony2 error : Case mismatch between loaded and declared class names:
Once have look on the folder name of your userbundle file.
Since, you have mentioned UserBunlde in your namespace **(namespace MyApp\UserBundle\Entity;) then,
Your folder name must be UserBundle too.
If you have named as userBundle so that such error occurs.
I'm working on a ZF2/Apigility application using Doctrine v2.4.2.
The model structure looks like this: an Asset has an Attachment (so, it's a 1:1 relationship):
The problem is that I cannot persist an Asset with an embedded Attachment and get the error
23000, 1048, Column 'attachment_linkassetuuid' cannot be null
It seems that Doctrine tries to save the Attachment first, cannot find a value for the column attachment_linkassetuuid, sets it to null, and the foreign key constraint is broken.
How to define the entities correctly and get the cascade persisting working?
Asset
namespace MyDoctrineDataAccess\Model\Entity;
...
/**
* Asset
*
* #ORM\Table(name="tbl_asset")
* #ORM\Entity
*/
class Asset
{
/**
* #var string #ORM\Column(name="asset_uuid", type="string", length=36, nullable=false)
* #ORM\Id
*/
private $uuid;
/**
* #var \MyDoctrineDataAccess\Model\Entity\Attachment
* #ORM\OneToOne(targetEntity="MyDoctrineDataAccess\Model\Entity\Attachment", mappedBy="asset", cascade={"remove", "persist"}, orphanRemoval=true)
*/
private $attachment;
...
}
/**
* #param \MyDoctrineDataAccess\Model\Entity\Attachment $attachment
*/
public function setAttachment($attachment) {
$this->attachment = $attachment;
return $this;
}
/**
* #return the $attachment
*/
public function getAttachment() {
return $this->attachment;
}
Attachment
namespace MyDoctrineDataAccess\Model\Entity;
...
/**
* Attachment
*
* #ORM\Table(name="tbl_attachment", indexes={#ORM\Index(name="fk_attachment_uuid", columns={"attachment_linkassetuuid"})})
* #ORM\Entity
*/
class Attachment
{
/**
*
* #var string #ORM\Column(name="attachment_uuid", type="string", length=36, nullable=false)
* #ORM\Id
*/
private $uuid;
/**
*
* #var \MyDoctrineDataAccess\Model\Entity\Asset
* #ORM\OneToOne(targetEntity="\MyDoctrineDataAccess\Model\Entity\Asset", inversedBy="attachment", cascade={"persist"})
* #ORM\JoinColumn(name="attachment_linkassetuuid", referencedColumnName="asset_uuid")
*/
private $asset;
...
}
/**
*
* #param \MyDoctrineDataAccess\Model\Entity\Asset $asset
*/
public function setAsset($asset)
{
$this->asset = $asset;
return $this;
}
/**
*
* #return the $asset
*
*/
public function getAsset()
{
return $this->asset;
}
AssetService
namespace MyApi\V1\Rest\Asset;
...
class AssetService implements ServiceManagerAwareInterface
{
...
public function saveAssets($data)
{
$entityManager = $this->serviceManager->get('Doctrine\ORM\EntityManager');
$assetRepository = $entityManager->getRepository('My\Model\Entity\Asset');
$hydratorManager = $this->serviceManager->get('hydratormanager');
$hydrator = $hydratorManager->get('My\\Model\\Entity\\Hydrator\\EntityHydrator');
foreach ($data as $assetData) {
$asset = new Asset();
$hydrator->hydrate($assetData, $asset);
$entityManager->persist($asset);
$entityManager->flush();
}
}
...
}
Since #JoinColumn defaults nullable to true according to the Doctrine documentation I don't really understand the error. But I do see that in your Attachment entity #table definition you declare an index:
indexes={#ORM\Index(name="fk_attachment_uuid", columns={"attachment_linkassetuuid"})}
Try once to remove this, rebuild your database and check if it solves your issue. If not then leave a comment and I will have another look.
Check the OneToOne example in the Doctrine documentation. Adding an #index like you do is not mentioned there. Doctrine will add the necessary indexes automatically to your relationship columns.
UPDATE:
I think the problem might be that Asset is not the owning side of the relationship. Check the documentation here. Try to change your setAttachment method like this:
public function setAttachment($attachment)
{
$this->attachment = $attachment;
$attachment->setAsset($this);
return $this;
}
Note People have marked this question as simmilar to others, but its not =- I am not using symfony and doctrine as a web framework, I am using symfony components with doctrine while using Slimphp as the actual web framework.
So while you might think I need an AppKernel I don't. I am using symfony components. The only issue here is that #UniqueEntity isn't working.
I have no idea what I am doing. I am getting the error:
Fatal error: Class 'doctrine.orm.validator.unique' not found in /var/www/html/image_upload_app/vendor/symfony/validator/ConstraintValidatorFactory.php on line 46
My AppKernel.php looks like:
namespace ImageUploader;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel {
public function registerBundles() {
$bundles = array(
new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle()
);
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader) {}
}
From there I created a bootstrap.php with the following contents:
/** ---------------------------------------------------------------- **/
// Lets Setup Doctrine.
/** ---------------------------------------------------------------- **/
require_once 'vendor/autoload.php';
$loader = require 'vendor/autoload.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
/**
* Set up Doctrine.
*/
class DoctrineSetup {
/**
* #var array $paths - where the entities live.
*/
protected $paths = array(APP_MODELS);
/**
* #var bool $isDevMode - Are we considered "in development."
*/
protected $isDevMode = false;
/**
* #var array $dbParams - The database paramters.
*/
protected $dbParams = null;
/**
* Constructor to set some core values.
*/
public function __construct(){
if (!file_exists('db_config.ini')) {
throw new \Exception(
'Missing db_config.ini. You can create this from the db_config_sample.ini'
);
}
$this->dbParams = array(
'driver' => 'pdo_mysql',
'user' => parse_ini_file('db_config.ini')['DB_USER'],
'password' => parse_ini_file('db_config.ini')['DB_PASSWORD'],
'dbname' => parse_ini_file('db_config.ini')['DB_NAME']
);
}
/**
* Get the entity manager for use through out the app.
*
* #return EntityManager
*/
public function getEntityManager() {
$config = Setup::createAnnotationMetadataConfiguration($this->paths, $this->isDevMode, null, null, false);
return EntityManager::create($this->dbParams, $config);
}
}
/**
* Function that can be called through out the app.
*
* #return EntityManager
*/
function getEntityManager() {
$ds = new DoctrineSetup();
return $ds->getEntityManager();
}
/**
* Function that returns the conection to the database.
*/
function getConnection() {
$ds = new DoctrineSetup();
return $ds->getEntityManager()->getConnection();
}
use \ImageUploader\AppKernel;
$kernel = new AppKernel();
$kernel->loadClassCache();
I am unsure why I keep getting this error, I have a model (entity) that looks as such:
namespace ImageUploader\Models;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* #ORM\Entity
* #ORM\Table(name="users")
* #UniqueEntity(fields="userName")
* #UniqueEntity(fields="email")
*/
class User {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
protected $id;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $firstName;
/**
* #ORM\Column(type="string", length=32, nullable=false)
* #Assert\NotBlank()
*/
protected $lastName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank(
* message = "Username cannot be blank"
* )
*/
protected $userName;
/**
* #ORM\Column(type="string", length=100, unique=true, nullable=false)
* #Assert\NotBlank()
* #Assert\Email(
* message = "The email you entered is invalid.",
* checkMX = true
* )
*/
protected $email;
/**
* #ORM\Column(type="string", length=500, nullable=false)
* #Assert\NotBlank(
* message = "The password field cannot be empty."
* )
*/
protected $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $created_at;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
protected $updated_at;
}
when I go to validate the model, I get the error listed above. I have installed doctrine bundle and I thought I set things up properly. But apparently not. Does any know know what I am doing wrong? Did I configure something wrong or not configure something at all?
You don't need to use the appkernel, I misunderstood your problem in your other question.
The problem is that you are using the UniqueValidator from the bridge. This is designed to work with the full-stack framework, not for standalone usage (only components are standalone).
This means you cannot use this constraint. Instead, you can use a pure Doctrine solution: #UniqueConstraint.
I've started working with Doctrine MongoDB ODM. I have a Document called Document which has an association originalFile to another document called File.
class Document extends AbstractDocument
{
/**
* #var integer $id
*
* #MongoDB\Id
*/
protected $id;
/**
* #var ImportSource
*
* #MongoDB\ReferenceOne(targetDocument="ImportSource", cascade="all", simple=true)
*/
protected $importSource;
/**
* #var DocumentState
*
* #MongoDB\ReferenceOne(targetDocument="DocumentState", cascade="all", simple=true)
*/
protected $state;
/**
* #var \DateTime $created
*
* #MongoDB\Date
*/
protected $created;
/**
* #var \DateTime $modified
*
* #MongoDB\Date
*/
protected $modified;
/**
* #var File $formattedFile
*
* #MongoDB\ReferenceOne(targetDocument="File", cascade="all")
*/
protected $formattedFile;
/**
* #var File $originalFilename
*
* #MongoDB\ReferenceOne(targetDocument="File", cascade="all")
*/
protected $originalFile;
//getters, setters etc..
}
File:
class File
{
/**
* #var string
*
* #MongoDB\Id
*/
protected $id;
/**
* #var FileType
*
* #MongoDB\ReferenceOne(targetDocument="FileType", cascade="all", simple=true)
*/
protected $type;
/**
* #var string
*
* #MongoDB\String
*/
protected $basename;
/**
* #var \DateTime
*
* #MongoDB\Date
*/
protected $created;
/**
* #var \DateTime
*
* #MongoDB\Date
*/
protected $deleted;
/**
* #var \MongoGridFSFile
*
* #MongoDB\File
*/
protected $file;
Storing the Document works without any problems. The Document and the File-Document are stored in MongoDB. When I'm loading the Document the $originalFile property is null. I have no clue what's missing. Is the mapping wrong or is this simply a bug in Doctrine?
Edit:
This is how I'm storing the documents:
//create if not exists
if ($documentObj === null) {
$documentObj = new Document();
$documentObj->setCreated(new \DateTime());
//create file
$file = new File();
} else {
$documentObj->setModified(new \DateTime());
//get file
$file = $documentObj->getOriginalFile();
}
$file->setFile($pathToFile);
//set file
$documentObj->setOriginalFile($file);
//set import source
$documentObj->setImportSource($source);
//store document
$documents[] = $this->storeDocument($documentObj, $documentFields);
//... method storeDocument fills other properties of the document and finally persits the document:
$this->manager->persist($documentObj);
$this->manager->flush();
I have no clue why, but it's working now... I was occupied with other projects for a few days, returned to this projects, ran my unit tests again and everything worked. Only thing I've done was a composer update. Maybe a bug correlating with my setup.
I got such problem, it is related to metadata cache, just run
bin/console cache:clear
bin/console doctrine:cache:clear-metadata
Also good to know these commands, if you are using symfony built-in cache
bin/console doctrine:cache:clear-query
bin/console doctrine:cache:clear-result
I'm usual working with symfony from the 2.1 or 2.2 versions.
Today i started a new project on the 2.3 and i'm encountering problems to create my custom entity repository.
My entity is:
<?php
namespace Acme\MyBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* AnnualProduction
*
* #ORM\Table(name="Annual_Production")
* #ORM\Entity(repositoryClass="Acme\MyBundle\Entity\AnnualproductionRepository")
*/
class AnnualProduction
{
/**
* #var string
*
* #ORM\Column(name="device_address", type="string", length=45, nullable=true)
*/
private $deviceAddress;
/**
* #var integer
*
* #ORM\Column(name="mese_1", type="integer", nullable=true)
*/
private $mese1;
/**
* #var integer
*
* #ORM\Column(name="mese_2", type="integer", nullable=true)
*/
SOME MISSING VAR SET AND GET
/**
* #var string
*
* #ORM\Column(name="sens_id", type="string", length=45)
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $sensId;
/**
* #var \DateTime
*
* #ORM\Column(name="AAAA", type="date")
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $aaaa;
/**
* Set deviceAddress
*
* #param string $deviceAddress
* #return AnnualProduction
*/
public function setDeviceAddress($deviceAddress)
{
$this->deviceAddress = $deviceAddress;
return $this;
}
/**
* Get deviceAddress
*
* #return string
*/
public function getDeviceAddress()
{
return $this->deviceAddress;
}
/**
* Set mese1
*
* #param integer $mese1
* #return AnnualProduction
*/
public function setMese1($mese1)
{
$this->mese1 = $mese1;
return $this;
}
/**
* Get mese1
*
* #return integer
*/
public function getMese1()
{
return $this->mese1;
}
/**
* Set sensId
*
* #param string $sensId
* #return AnnualProduction
*/
public function setSensId($sensId)
{
$this->sensId = $sensId;
return $this;
}
/**
* Get sensId
*
* #return string
*/
public function getSensId()
{
return $this->sensId;
}
/**
* Set aaaa
*
* #param \DateTime $aaaa
* #return AnnualProduction
*/
public function setAaaa($aaaa)
{
$this->aaaa = $aaaa;
return $this;
}
/**
* Get aaaa
*
* #return \DateTime
*/
public function getAaaa()
{
return $this->aaaa;
}
}
I dont write all variable and get and sets functions.
I've created a repository file: Acme\MyBundle\Entity\AnnualproductionRepository.php
The code for the repository file is the following:
<?php
namespace Acme\MyBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Acme\MyBundle\Entity\AnnualProduction;
class AnnualproductionRepository extends EntityRepository
{
public function findByYearMonthDay($anno, $mese, $giorno, $sensId)
{
$query = $this->getEntityManager()
->createQuery(" SOME QUERY HERE")->setParameters(array(SOME PARAMETERS HERE));
return $query->getSingleResult();
}
}
I call the repository in one of my controller, with the following code:
<?php
namespace Acme\MyBundle\Controller;
use Acme\MyBundle\Entity\AnnualProduction;
use Acme\MyBundle\Entity;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\Date;
class DataController extends Controller{
public function indexUserAction(){
*
*
*
*
*
$DailyProduction=$DailyProduction+$em->getRepository('AcmeMyBundle:AnnualProduction')->findByYearMonthDay($year, $month, $day, $productionSensor);
*
*
*
*
}
}
But i get this error like the repository doesnt exist and the controller get the function name like a default findBy* on one of the Entity attributes.
ERROR:
*> Entity 'Acme\MyBundle\Entity\AnnualProduction' has no field
'yearMonthDay'. You can therefore not call 'findByYearMonthDay' on the
entities' repository***
Have you some advise to solve this problem? the code seems to be identical to the one i usualy add to include custom entity repository in symfony 2.2 but for some reason it refuse to work.
Tx for your time and Help.
Problem Solved, the fact was that the entity.orm.xml files, stored in /src/acme/myBundle/config/doctrine, have an hight priority over the entity files, so every modification to the entity that i was doing wasent readed.
SOLUTION: Delete all the entity.orm.xml files after done the annotation ed the generation of the entity via terminal php command.
The namespace for your repository is wrong. You should have Acme\MyBundle\Entity\Repository for a namespace instead. The path to your file ought to then be Acme/MyBundle/Entity/Repository/AnnualProduction.
You should also let doctrine generate all your entities for you via
php app/console doctrine:generate:entities Acme
You will then see a folder called Repositories in your Entities folder and thats where all the entities need to be stored.