Symfony-2.3 entity repository error - php

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.

Related

Embedded forms relations doctrine

in my symfony app, i'm using embedded forms. In my case, an object "CompetenceGroupe" can have multiple objects "CompetenceItem", but an object "CompetenceItem" belongs to only one object "CompetenceGroupe", so the relation is manyToOne.
The form work perfectly, and I have two tables (one for each entity), and it's well saved in the database.
But when I select an CompetenceGroupe object with doctrine in my controller, I have all informations of the object, and he's got an empty "competenceItems" property, so I can't retrieve the childs object (CompetenceItem).
My "CompetenceGroupe" entity :
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="competences_groupes")
*/
class CompetenceGroupe
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id_competence_groupe;
/**
* #var User $user
*
* #ORM\ManyToOne(targetEntity="User", cascade={"persist", "merge"})
* #ORM\JoinColumn(name="id_user", referencedColumnName="id_user", nullable=false)
*/
private $user;
/**
* #ORM\Column(type="string", length=60, nullable=true)
*/
protected $titre;
protected $competence_items;
public function __construct()
{
$this->competence_items = new ArrayCollection();
}
public function getCompetenceItems()
{
return $this->competence_items;
}
/**
* Get idCompetenceGroupe
*
* #return integer
*/
public function getIdCompetenceGroupe()
{
return $this->id_competence_groupe;
}
/**
* Set titre
*
* #param string $titre
*
* #return CompetenceGroupe
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set user
*
* #param \AppBundle\Entity\User $user
*
* #return CompetenceGroupe
*/
public function setUser(\AppBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \AppBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
public function addItem(CompetenceItem $item)
{
$this->competence_items->add($item);
}
public function removeItem(CompetenceItem $item)
{
// ...
}
/**
* Set competenceItems
*
* #param \AppBundle\Entity\CompetenceItem $competenceItems
*
* #return CompetenceGroupe
*/
public function setCompetenceItems(\AppBundle\Entity\CompetenceItem $competenceItems = null)
{
$this->competence_items = $competenceItems;
return $this;
}
}
And my "CompetenceItem" entity :
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="competences_items")
*/
class CompetenceItem
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id_competence_item;
/**
* #ORM\Column(type="string", length=60, nullable=false)
*/
protected $libelle;
/**
* #var CompetenceNiveau $niveau
*
* #ORM\ManyToOne(targetEntity="CompetenceNiveau", cascade={"persist", "merge"})
* #ORM\JoinColumn(name="id_competence_niveau", referencedColumnName="id_competence_niveau", nullable=true)
*/
private $niveau;
/**
* #var CompetenceGroupe $competence_groupe
*
* #ORM\ManyToOne(targetEntity="CompetenceGroupe", cascade={"persist", "merge"})
* #ORM\JoinColumn(name="id_competence_groupe", referencedColumnName="id_competence_groupe", nullable=false)
*/
private $competence_groupe;
/**
* Get idCompetenceItem
*
* #return integer
*/
public function getIdCompetenceItem()
{
return $this->id_competence_item;
}
/**
* Set libelle
*
* #param string $libelle
*
* #return CompetenceItem
*/
public function setLibelle($libelle)
{
$this->libelle = $libelle;
return $this;
}
/**
* Get libelle
*
* #return string
*/
public function getLibelle()
{
return $this->libelle;
}
/**
* Set niveau
*
* #param \AppBundle\Entity\CompetenceNiveau $niveau
*
* #return CompetenceItem
*/
public function setNiveau(\AppBundle\Entity\CompetenceNiveau $niveau = null)
{
$this->niveau = $niveau;
return $this;
}
/**
* Get niveau
*
* #return \AppBundle\Entity\CompetenceNiveau
*/
public function getNiveau()
{
return $this->niveau;
}
/**
* Set competenceGroupe
*
* #param \AppBundle\Entity\CompetenceGroupe $competenceGroupe
*
* #return CompetenceItem
*/
public function setCompetenceGroupe(\AppBundle\Entity\CompetenceGroupe $competenceGroupe)
{
$this->competence_groupe = $competenceGroupe;
return $this;
}
/**
* Get competenceGroupe
*
* #return \AppBundle\Entity\CompetenceGroupe
*/
public function getCompetenceGroupe()
{
return $this->competence_groupe;
}
}
I think I have a missing annotation of the "competence_items" property in the CompetenceGroupe entity, but i'm really not sure ...
Thanks for your help !
A good practice may be to have a competence form, which would be call inside your competence group form
You may add a CollectionType as parrent and include query to search which competence already exist
There are some good example with post form type in symfony demo blog
Or you can use form events (onSubmit, preSubmit, etc...) to charge your entity with your required competence. This example show a message form which allow to choose friend from preset data, this is a good example.
You have tow choice , even to create a Many-To-One, Unidirectional , in this case , you need clean some code , take a look:
In CompetenceGroupe class :
class CompetenceGroupe
{
/**
* Many competence have One Group.
* #ManyToOne(targetEntity="CompetenceItem")
* #JoinColumn(name="id_competence_item", referencedColumnName="id_competence_item")
*/
protected $competence_items;
public function __construct()
{
// $this->competence_items = new ArrayCollection();
//delete that line
}
In CompetenceItem class :
class CompetenceItem
{
You need to delete private $competence_groupe; attribute with his annotation :
By this way, when you dump a CompetenceGroupe object you gonna find the competence items.
Also, you can do it with One-To-Many, Bidirectional ,if you want to get the data from the inverse side and from the owning side .
EDIT: If one competenceGroupe can have many competenceItems, then that is a OneToMany relationship; this is the inverse side of the relationship as defined by doctrine, but that is ok. Your question asked how to pull a competenceGroupe and retrieve all related competenceItems. You can do this by making the competenceItems an ArrayCollection in your CompetenceGroupe entity, just as you have done. You do have to define that further in the annotation, see (updated) code below.
For an ArrayCollection, you can remove your method setCompetenceItems and instead define a method addCompetenceItem in your CompetenceGroupe entity.
class CompetenceGroupe
{
/**
* #ORM\OneToMany(targetEntity="CompetenceItem", mappedBy="competence_groupe")
*/
protected $competenceItems;
public function __construct()
{
$this->competenceItems= new ArrayCollection();
}
/**
* Add competenceItem
*
* #param CompetenceItem $competenceItem
* #return CompetenceGroupe
*/
public function addCompetenceItem(CompetenceItem $competenceItem)
{
$this->competence_items->add($competenceItem);
return $this;
}
}
You'll also need to define the owning side to make all this work.

Doctrine 2 many-to-many with MappedSuperclass in Zend framework 2

I am new to Doctrine2 and trying to create entities for the following DB structure:
I want to have all machine parts as an array in one attribute of the machine class. I tried this:
class Machine {
....
/**
* #var array
* #ORM\OneToMany(targetEntity="MachineHasPart", mappedBy="machine", cascade={"persist", "remove"}, orphanRemoval=TRUE)
*/
private $parts;
....
public function getParts () {
return array_map(
function ($machineHasPart) {
return $machineHasPart->getPart();
},
$this->parts->toArray()
);
}
}
Where MachineHasPart is a #MappedSuperclass for the intermediate entities/tables (like machineHasCylinder etc), but it failed with:
An exception occurred while executing 'SELECT FROM machineHasPart t0'.
Should I restructure my database to use ORM here? Or there is a solution for my case?
You cannot query a #MappedSuperClass. This is also mentioned in the Doctrine2 documentation in chapter 6.1. Mapped Superclasses:
A mapped superclass cannot be an entity, it is not query-able and persistent
This means you have to either change the target entity to something queryable or you have to make MachineHasPart to a entity and change to single table inheritance.
When I look at your database structure I would suggest changing your Machine entity to have three independent relationships for the parts. One for Belt, one for Cylinder and one for Gear.
Then instead of a generic getParts you will have three methods getBelts, getCylinders and getGears.
If that is really not what you want then you can leave a comment.
UPDATE
You can solve it also with class inheritance. First make a base class Part that is also an entity and use it in the other classes Belt, Cylinder and Gear:
Part:
<?php
namespace Machine\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Part
*
* #ORM\Entity
* #ORM\Table("part")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="discriminator", type="string")
* #ORM\DiscriminatorMap({
* "part" = "Part",
* "gear" = "Gear",
* "cylinder" = "Cylinder",
* "belt" = "Belt",
* })
* #property int $id
*/
class Part
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var Machine
* #ORM\ManyToOne(targetEntity="Machine\Entity\Machine", inversedBy="parts")
* #ORM\JoinColumn(name="machine_id", referencedColumnName="id", nullable=true)
*/
protected $machine;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
* #return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
//... add setters and getters for machine as normal ...
}
Extend this class in your other parts:
Belt:
<?php
namespace Machine\Entity;
/**
* Belt
*
* #ORM\Entity
*/
class Belt extends Part
{
}
Cylinder:
<?php
namespace Machine\Entity;
/**
* Cylinder
*
* #ORM\Entity
*/
class Cylinder extends Part
{
}
Gear:
<?php
namespace Machine\Entity;
/**
* Gear
*
* #ORM\Entity
*/
class Gear extends Part
{
}
Now in your machine relate to the parts like as follows.
Machine:
<?php
namespace Machine\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Machine
*
* #ORM\Entity
* #ORM\Table("machine")
* #property int $id
*/
class Machine
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set id.
*
* #param int $id
* #return self
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* #var Collection
* #ORM\OneToMany(targetEntity="Machine\Entity\Part", mappedBy="machine")
*/
protected $parts;
public function __constuct()
{
$parts = new ArrayCollection();
}
/**
*
* #return Collection
*/
public function getParts()
{
return $this->parts;
}
//... add setters and getters for parts as normal ...
}
Extend this class in your other parts:
Reading further in the Doctrine2 documentation in chapter 6.1. Mapped Superclasses (referred to by #Wilt):
... Furthermore Many-To-Many associations are only possible if the mapped superclass is only used in exactly one entity at the moment...
This means in this case the ORM mapping doesn't help. I cannot gather the data of all three entities MachineHasCylinder, MachineHasBelt and MachineHasGear through a MappedSupperclass at the same time.
I think using DQL or Native SQL is the only solution for this problem.

Doctrine annotations try to autoload wrong annotation

I try to use Symfony 2.6/Doctrine 2 on Ubuntu 14.04 with php5.5.9/mysql5.5. But i get very strange error and couldn't find any solution.
I create very simple entity with doctrine:generate:entity command. Everything is just fine. But when I try to create table with doctrine:schema:update command I get an imposible to fix error :)
[Doctrine\Common\Annotations\AnnotationException]
[Semantical Error] The annotation "#Doctrine\ORM\Mapping\I" in property AppBundle\Entity\Language::$id does not exist, or could not be auto-loaded.
Well, actually it's right. There is nothing such #Doctrine\ORM\Mapping\I.
It's all about #ORM\Id. When I change #ORM\Id, the error also changes. I change it to #ORM\Hello, the error changes as #Doctrine\ORM\Mapping\Hello. But when I change it to #ORM\Isthisreal, the error stand still as #Doctrine\ORM\Mapping\I.
I thing there is some parsing error about case sensitiveness. But couldn't find any sollution. I tried lots of things but nothing changes. Here is my simple entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Language
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\LanguageRepository")
*/
class Language
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var boolean
*
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #var string
*
* #ORM\Column(name="iso", type="string", length=2)
*/
private $iso;
/**
* Get id
*
* #return integer
*/
public function getid()
{
return $this->id;
}
/**
* Set isActive
*
* #param boolean $isActive
* #return Language
*/
public function setisActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getisActive()
{
return $this->isActive;
}
/**
* Set iso
*
* #param string $iso
* #return Language
*/
public function setiso($iso)
{
$this->iso = $iso;
return $this;
}
/**
* Get iso
*
* #return string
*/
public function getiso()
{
return $this->iso;
}
}
Try run this before doctrine:schema:update
export LC_ALL=C

error when trying to register in Symfony2

I am new in symfony2, I would like to register some user in my profile_tbl.
here is my code in the controller.
<?php
namespace Ai\QABlogBundle\Controller;
use Ai\QABlogBundle\Entity\Profile_tbl;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class QABlogController extends Controller
{
/**
*#Route("/" , name= "home")
*/
public function homeAction()
{
return $this->render('AiQABlogBundle:QABlog:primaries/index.html.twig');
}
/**
*#Route("/register/" ,name= "register")
*/
public function registerAction(Request $request)
{
$profile = new Profile_tbl();
$form = $this -> createFormBuilder($profile)
-> add ('fname' , 'text')
-> add ('lname' , 'text')
-> add ('gender' , 'text')
-> add ('email' , 'text')
-> add ('register' , 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($profile);
$em->flush();
return new Response('News added successfuly');
}
$build['form'] = $form->createView();
return $this->render('AiQABlogBundle:QABlog:primaries/registration.html.twig', $build);
}
}
When I try to run it in my browser it gives an error
"Attempted to load class "Profile_tbl" from namespace "Ai\QABlogBundle\Entity".
Did you forget a "use" statement for another namespace?"
I don't know what is wrong .. Can you help me?
my Profile_tbl entity
<?php
namespace Ai\QABlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Profile_tbl
*
* #ORM\Table()
* #ORM\Entity
*/
class Profile_tbl
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="fname", type="string", length=255)
*/
private $fname;
/**
* #var string
*
* #ORM\Column(name="lname", type="string", length=255)
*/
private $lname;
/**
* #var string
*
* #ORM\Column(name="gender", type="string", length=255)
*/
private $gender;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set fname
*
* #param string $fname
* #return Profile_tbl
*/
public function setFname($fname)
{
$this->fname = $fname;
return $this;
}
/**
* Get fname
*
* #return string
*/
public function getFname()
{
return $this->fname;
}
/**
* Set lname
*
* #param string $lname
* #return Profile_tbl
*/
public function setLname($lname)
{
$this->lname = $lname;
return $this;
}
/**
* Get lname
*
* #return string
*/
public function getLname()
{
return $this->lname;
}
/**
* Set gender
*
* #param string $gender
* #return Profile_tbl
*/
public function setGender($gender)
{
$this->gender = $gender;
return $this;
}
/**
* Get gender
*
* #return string
*/
public function getGender()
{
return $this->gender;
}
/**
* Set email
*
* #param string $email
* #return Profile_tbl
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
}
I try to rename or make another entity ..
steps that I tried to generate my new entity.
Creating Database:
php app/console doctrine:database:create
Generate Entity:
php app/console doctrine:generate:entity
Generate the Getters and Setters:
php app/console doctrine:generate:entities AiQABlogBundle
after this I run it in my browser.
and gives me an error ,
Attempted to load class "Profile" from namespace "Ai\QABlogBundle\Controller".
Did you forget a "use" statement for e.g. "Twig_Profiler_Profile" or "Symfony\Component\HttpKernel\Profiler\Profile"?
This happened to me a few times. It usually happens when I copy-paste an old class file to create a new class. Check your classname and the filename of the file containing your class; they should be the same. In your case they should be Profile_tbl and Profile_tbl .php respectively.
Update
Profile_tbl is converted to Profile/tbl.php as per the PSR-0 autoload convention which Composer uses by default to load classes inside the src/ directory. You'll have to rename the class to something that does not use an underscore e.g. ProfileTbl or simply Profile.
// This should be in the file: src/Ai/QABlogBundle/Entity/Profile.php
namespace Ai\QABlogBundle\Entity;
/**
* Profile
*
* #ORM\Table()
* #ORM\Entity
*/
class Profile
{
// ...
}
Credits to Pazi for pointing this out.

Symfony2, Doctrine2 - force update - table already exists on many-to-many relation

After I successfuly created TaskBundle with One-to-Many relation between category and tasks, now I'm trying to create a new TaskBundle with Many-to-Many relation. I get also problem with checking checkbox in this relation, but now it is not a primary problem (maybe after solving this). I deleted all tables, which is TaskBundle using and trying to create a new, but here is problem (description at the bottom).
My Task object:
<?php
namespace Acme\TaskBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="tasks")
*/
class Task
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=200)
* #Assert\NotBlank(
* message = "Task is empty"
* )
* #Assert\Length(
* min = "3",
* minMessage = "Task is too short"
* )
*/
protected $task;
/**
* #ORM\Column(type="datetime")
* #Assert\NotBlank()
* #Assert\Type("\DateTime")
*/
protected $dueDate;
/**
* #Assert\True(message = "You have to agree.")
*/
protected $accepted;
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
* #ORM\JoinTable(name="categories")
*/
protected $category;
/**
* Constructor
*/
public function __construct()
{
$this->category = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set task
*
* #param string $task
* #return Task
*/
public function setTask($task)
{
$this->task = $task;
return $this;
}
/**
* Get task
*
* #return string
*/
public function getTask()
{
return $this->task;
}
/**
* Set dueDate
*
* #param \DateTime $dueDate
* #return Task
*/
public function setDueDate($dueDate)
{
$this->dueDate = $dueDate;
return $this;
}
/**
* Get dueDate
*
* #return \DateTime
*/
public function getDueDate()
{
return $this->dueDate;
}
/**
* Add category
*
* #param \Acme\TaskBundle\Entity\Category $category
* #return Task
*/
public function addCategory(\Acme\TaskBundle\Entity\Category $category)
{
$this->category[] = $category;
return $this;
}
/**
* Remove category
*
* #param \Acme\TaskBundle\Entity\Category $category
*/
public function removeCategory(\Acme\TaskBundle\Entity\Category $category)
{
$this->category->removeElement($category);
}
/**
* Get category
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCategory()
{
return $this->category;
}
}
and Category object
<?php
namespace Acme\TaskBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="categories")
*/
class Category
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=200, unique=true)
* #Assert\NotNull(message="Categories cannot be empty", groups = {"adding"})
*/
protected $name;
/**
* #ORM\ManyToMany(targetEntity="Task", mappedBy="category")
*/
private $tasks;
public function __toString()
{
return strval($this->name);
}
/**
* Constructor
*/
public function __construct()
{
$this->tasks = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Category
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add tasks
*
* #param \Acme\TaskBundle\Entity\Task $tasks
* #return Category
*/
public function addTask(\Acme\TaskBundle\Entity\Task $tasks)
{
$this->tasks[] = $tasks;
return $this;
}
/**
* Remove tasks
*
* #param \Acme\TaskBundle\Entity\Task $tasks
*/
public function removeTask(\Acme\TaskBundle\Entity\Task $tasks)
{
$this->tasks->removeElement($tasks);
}
/**
* Get tasks
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTasks()
{
return $this->tasks;
}
}
So, after i put doctrine:schema:update --force i'll get error: Table 'symfony.categories' already exists. I've tried to delete all caches, but same problem. Any idea?
There's only problem, if it is as m2m relation.
PS: I was looking for this problem at the Google, but no one answers at this problem. There were only questions, but not correct answers, where the problem is and how to solve it.
Looks like you already have table named "categories" in that database. Remove this line #ORM\JoinTable(name="categories") and try without it.
P.S. "Categories" is really a strange name for join table. You should probably follow some conventions and let doctrine name it. Common names for join tables are category_task or category2task as they are more self-explanatory. Nothing that important, just trying to suggest what I consider good practice.
The thing is that doctrine doesn't understand how your existing table should be used. But you can give him some help.
You have two options :
You don't care about the existing table : simple, you can remove the #ORM\JoinTable(name="categories") annotation, and doctrine will create an other table etc.
You want to keep your existing table, which sounds pretty logical : you have to be more explicit in your annotation by adding #ORM\JoinColumn annotation.
Here is an example:
class
<?php
...
/**
* #ORM\Entity
* #ORM\Table(name="tasks")
*/
class Task
{
...
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
* #ORM\JoinTable(name="categories",
* joinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="task_id", referencedColumnName="id")})
*/
protected $category;
...
}
and Category object
<?php
...
/**
* #ORM\Entity
* #ORM\Table(name="categories")
*/
class Category
{
...
/**
* #ORM\ManyToMany(targetEntity="Task", mappedBy="category")
* #ORM\JoinTable(name="categories",
* joinColumns={#ORM\JoinColumn(name="task_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="category_id", referencedColumnName="id")})
*/
private $tasks;
...
Doing so, you will be able to keep your table without any doctrine error.
My fix for this, as far as I can tell, was a case-sensitivity issue with table names. Doctrine let me create a Users and a users table but afterwards would die on migrations:diff or migrations:migrate .
I used the -vvv option to get more detail on this error message; it seems that the error happens when Doctrine is loading up its own internal representation of the current database's schema. So if your current database has table names that Doctrine doesn't understand (like two tables that are identical, case-insensitive) then it will blow up in this fashion.
Seems like most of the answers above assume that the error is in your code, but in my case it was in the database.
I got this error with 2 ManyToMany targeting the same entity (User in the exemple below).
To create the table name doctrine use the entity and target entity name.
So in my case it was trying to create two time the table thread_user
To debug this it's easy. Just use the '#ORM\JoinTable' annotation and specify the table name.
Here is a working exemple.
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User")
* #ORM\JoinTable(name="thread_participant")
*/
private $participants;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\User")
* #ORM\JoinTable(name="thread_recipient")
*/
private $recipients;
in Symfony4.1 you can force the migration using the migration version
doctrine:migrations:execute <migration version>
ex
for migration version123456.php use
doctrine:migrations:execute 123456
there is another using the table name ,you can search it in your project . Maby be demo,I think it...
sorry for my chinese english !
Try to drop everything inside of your proxy directory.
I fix same issue after check other entities on each bundles, be aware of this.

Categories