I'm trying to put into a table called question tag an element so:
//the question with Id 1 exist already
$question = new Question();
$question->setId(1);
//the tag with name PYTHON exist already
$tag = new Tag();
$tag->setName("PYTHON");
$questionTag = new QuestionTag();
$questionTag->setQuestion($question);
$questionTag->setTag($tag);
//now I call a service to put the item into DB
$questionTagPF = $this->get('facade.QuestionTagFacade');
$res = $questionTagPF->create($questionTag);
This is the method to save the entity:
public function create( $entity ) {
$this->entityManager->getConnection()->beginTransaction();
try {
$this->entityManager->persist($entity);
$this->entityManager->flush();
$this->entityManager->getConnection()->commit();
return true;
} catch ( Exception $e ) {
$this->entityManager->getConnection()->rollBack();
return false;
}
}
And these are the entity classes:
relation (between question and tag):
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* QuestionTag
*
* #ORM\Table(name="question_tag", indexes={#ORM\Index(name="question", columns={"question"}), #ORM\Index(name="index_question_tag", columns={"tag"})})
* #ORM\Entity
*/
class QuestionTag
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \AppBundle\Entity\Question
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Question", cascade={ "persist" })
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question", referencedColumnName="id")
* })
*/
private $question;
/**
* #var \AppBundle\Entity\Tag
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Tag", cascade={ "persist" })
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="tag", referencedColumnName="name")
* })
*/
private $tag;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set question
*
* #param \AppBundle\Entity\Question $question
*
* #return QuestionTag
*/
public function setQuestion(\AppBundle\Entity\Question $question = null)
{
$this->question = $question;
return $this;
}
/**
* Get question
*
* #return \AppBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
/**
* Set tag
*
* #param \AppBundle\Entity\Tag $tag
*
* #return QuestionTag
*/
public function setTag(\AppBundle\Entity\Tag $tag = null)
{
$this->tag = $tag;
return $this;
}
/**
* Get tag
*
* #return \AppBundle\Entity\Tag
*/
public function getTag()
{
return $this->tag;
}
}
question entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Question
*
* #ORM\Table(name="question", indexes={#ORM\Index(name="index_question_title", columns={"title"}), #ORM\Index(name="index_question_creation", columns={"creation_date"}), #ORM\Index(name="index_question_completed", columns={"completed"}), #ORM\Index(name="index_question_subject", columns={"subject"}), #ORM\Index(name="index_question_user", columns={"user_platform"})})
* #ORM\Entity
*/
class Question
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=50, nullable=false)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="text", type="string", length=1000, nullable=true)
*/
private $text;
/**
* #var \DateTime
*
* #ORM\Column(name="creation_date", type="date", nullable=false)
*/
private $creationDate;
/**
* #var boolean
*
* #ORM\Column(name="completed", type="boolean", nullable=true)
*/
private $completed = '0';
/**
* #var integer
*
* #ORM\Column(name="level", type="integer", nullable=true)
*/
private $level = '1';
/**
* #var \AppBundle\Entity\Subject
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Subject", cascade={ "persist" })
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="subject", referencedColumnName="name")
* })
*/
private $subject;
/**
* #var \AppBundle\Entity\UserPlatform
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\UserPlatform", cascade={ "persist" })
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="user_platform", referencedColumnName="username")
* })
*/
private $userPlatform;
/**
* Set id
*
* #param string $id
*
* #return Question
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Question
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set text
*
* #param string $text
*
* #return Question
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get text
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set creationDate
*
* #param \DateTime $creationDate
*
* #return Question
*/
public function setCreationDate($creationDate)
{
$this->creationDate = $creationDate;
return $this;
}
/**
* Get creationDate
*
* #return \DateTime
*/
public function getCreationDate()
{
return $this->creationDate;
}
/**
* Set completed
*
* #param boolean $completed
*
* #return Question
*/
public function setCompleted($completed)
{
$this->completed = $completed;
return $this;
}
/**
* Get completed
*
* #return boolean
*/
public function getCompleted()
{
return $this->completed;
}
/**
* Set level
*
* #param integer $level
*
* #return Question
*/
public function setLevel($level)
{
$this->level = $level;
return $this;
}
/**
* Get level
*
* #return integer
*/
public function getLevel()
{
return $this->level;
}
/**
* Set subject
*
* #param \AppBundle\Entity\Subject $subject
*
* #return Question
*/
public function setSubject(\AppBundle\Entity\Subject $subject = null)
{
$this->subject = $subject;
return $this;
}
/**
* Get subject
*
* #return \AppBundle\Entity\Subject
*/
public function getSubject()
{
return $this->subject;
}
/**
* Set userPlatform
*
* #param \AppBundle\Entity\UserPlatform $userPlatform
*
* #return Question
*/
public function setUserPlatform(\AppBundle\Entity\UserPlatform $userPlatform = null)
{
$this->userPlatform = $userPlatform;
return $this;
}
/**
* Get userPlatform
*
* #return \AppBundle\Entity\UserPlatform
*/
public function getUserPlatform()
{
return $this->userPlatform;
}
}
tag entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Tag
*
* #ORM\Table(name="tag")
* #ORM\Entity
*/
class Tag
{
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=20)
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*/
private $name = '';
/**
* Set name
*
* #param string $name
*
* #return tag
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
when I try to put a value into table question_tag I have this error:
An exception occurred while executing 'INSERT INTO tag (name) VALUES (?)' with params ["PYTHON"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'PYTHON' for key 'PRIMARY'
Why?
It should not avoid entering a value if it already exists in the database? if this should be made explicit, how should I do?
thank you
In Symfony2 you have this things called Validators their job is to validate an object based on constraints so in your case you could use the following constraint in your tag entity
http://symfony.com/doc/current/reference/constraints/UniqueEntity.html
And then call to the validator service in your controller. You could avoid this step if you use FormTypes for your classes they automatically validate the object with the validator service.
http://symfony.com/doc/current/book/forms.html
Actually you could use the forms to validate data structure.. but that is offtopic
.....
The other way you could do this is by selecting the tag you want to insert and check if there is a result if not well then you can insert the tag if it exists you just recover it from the database and use the existing one
the problem was with the parameters that I give to the method to put data into db, so this code:
//the question with Id 1 exist already
$question = new Question();
$question->setId(1);
//the tag with name PYTHON exist already
$tag = new Tag();
$tag->setName("PYTHON");
$questionTag = new QuestionTag();
$questionTag->setQuestion($question);
$questionTag->setTag($tag);
//now I call a service to put the item into DB
$questionTagPF = $this->get('facade.QuestionTagFacade');
$res = $questionTagPF->create($questionTag);
have to be written so:
//the question with Id 1 exist already
$question = $this->getDoctrine()->getManager()->getReference('AppBundle:Question',"1");
//the tag with name PYTHON exist already
$tag = $this->getDoctrine()->getManager()->getReference('AppBundle:Tag',"PYTHON");
$questionTag = new QuestionTag();
$questionTag->setQuestion($question);
$questionTag->setTag($tag);
//now I call a service to put the item into DB
$questionTagPF = $this->get('facade.QuestionTagFacade');
$res = $questionTagPF->create($questionTag);
The problem was that to insert a value into a relation you have to take values through the manager!
Related
In my User entity, I have this:
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
* #ORM\OneToMany(targetEntity="Blog\BlogBundle\Entity \Entry",mappedBy="author")
*/
protected $entries;
This is my full Entry entity.
<?php
namespace Blog\BlogBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Entry
*
* #ORM\Table(name="entry")
* #ORM\Entity(repositoryClass="Blog\BlogBundle\Repository\EntryRepository")
*/
class Entry
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var string
*
* #ORM\Column(name="book", type="text")
*/
private $book;
/**
* #var \DateTime
*
* #ORM\Column(name="timestamp", type="datetime")
*/
private $timestamp;
/**
* #var AppBundle\Entity
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User",inversedBy="entries")
* #ORM\JoinColumn(name="author", referencedColumnName="id")
*/
private $author;
/**
* #var \Doctrine\Common\Collections\ArrayCollection
* #ORM\OneToMany(targetEntity="Blog\BlogBundle\Entity\Reviews",mappedBy="book_id")
*/
protected $reviews;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
*
* #return Entry
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set book
*
* #param string $book
*
* #return Entry
*/
public function setBook($book)
{
$this->book = $book;
return $this;
}
/**
* Get book
*
* #return string
*/
public function getBook()
{
return $this->book;
}
/**
* Set timestamp
*
* #param \DateTime $timestamp
*
* #return Entry
*/
public function setTimestamp($timestamp)
{
$this->timestamp = $timestamp;
return $this;
}
/**
* Get timestamp
*
* #return \DateTime
*/
public function getTimestamp()
{
return $this->timestamp;
}
/**
* Set author
*
* #param \AppBundle\Entity\User $author
*
* #return Entry
*/
public function setAuthor(\AppBundle\Entity\User $author = null)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* #return \AppBundle\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
/**
* Get author ID
*
* #return \AppBundle\Entity\User
*/
public function getAuthorId()
{
$id = $this->author;
return $this->$id;
}
public function __toString()
{
try {
return (string) $this->id;
} catch (Exception $exception) {
return '';
}
}
}
From this piece of code I am trying to retrieve Author ID, but instead author name is being returned. I presume this is because I am converting to string at the end. If I remove it, I get this error: symfony2 Catchable Fatal Error: Object of class could not be converted to string
To get the link, I am doing the following:
Setting path author with parameter of id in routing.yml of the bundle which triggers authorAction($id) inside BookController. Expecting an integer to be passed.
authorAction($id) sets up Doctrine Manager, calls getAllBooksByAuthor() function in a repository where a relevant query returns all books by author with id and renders the twig template.
The link is generated in the twig template, but instead parameter passed is author name - which is a string, not an integer.
How can I do it so author ID is passed instead of author name?
I'm stuck here and I need Entry entity to be able to handle both strings and integers.
Specifically this is the change:
/**
* Get author ID
*
* #return intger
*/
public function getAuthorId()
{
return $this->author->getId();
}
Note: the #return documentation should be changed to show it's returning an integer.
I've got problem with relations ManyToOne.
I have 2 entities:
namespace MyApp\PanelBundle\Entity;
use MyApp\PanelBundle\Entity\SupportMessagesThreads;
use Doctrine\ORM\Mapping as ORM;
/**
* SupportMessages
*
* #ORM\Table(name="support_messages")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesRepository")
*/
class SupportMessages
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="thread_id", type="integer")
*/
private $thread_id;
/**
* #var int
*
* #ORM\Column(name="sender", type="integer")
*/
private $sender;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* #var bool
*
* #ORM\Column(name="is_read_sender", type="boolean")
*/
private $is_read_sender;
/**
* #var bool
*
* #ORM\Column(name="is_read_recipient", type="boolean")
*/
private $is_read_recipient;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\ManyToOne(targetEntity="SupportMessagesThreads", inversedBy="messages")
* #ORM\JoinColumn(name="thread_id", referencedColumnName="id")
*/
private $thread;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
/**
* Get threadId
*
* #return int
*/
public function getThreadId()
{
return $this->thread_id;
}
/**
* Set sender
*
* #param integer $sender
*
* #return SupportMessages
*/
public function setSender($sender)
{
$this->sender = $sender;
return $this;
}
/**
* Get sender
*
* #return int
*/
public function getSender()
{
return $this->sender;
}
/**
* Set content
*
* #param string $content
*
* #return SupportMessages
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set isReadSender
*
* #param boolean $isReadSender
*
* #return SupportMessages
*/
public function setIsReadSender($isReadSender)
{
$this->is_read_sender = $isReadSender;
return $this;
}
/**
* Get isReadSender
*
* #return bool
*/
public function getIsReadSender()
{
return $this->is_read_sender;
}
/**
* Set isReadRecipient
*
* #param boolean $isReadRecipient
*
* #return SupportMessages
*/
public function setIsReadRecipient($isReadRecipient)
{
$this->is_read_recipient = $isReadRecipient;
return $this;
}
/**
* Get isReadRecipient
*
* #return bool
*/
public function getIsReadRecipient()
{
return $this->is_read_recipient;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessages
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
AND
<?php
namespace MyApp\PanelBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use MyApp\PanelBundle\Entity\SupportMessages;
/**
* SupportMessagesThreads
*
* #ORM\Table(name="support_messages_threads")
* #ORM\Entity(repositoryClass="MyApp\PanelBundle\Repository\SupportMessagesThreadsRepository")
*/
class SupportMessagesThreads
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var int
*
* #ORM\Column(name="user_id", type="integer")
*/
private $user_id;
/**
* #var int
*
* #ORM\Column(name="recipient", type="integer")
*/
private $recipient;
/**
* #var string
*
* #ORM\Column(name="title", type="string")
*/
private $title;
/**
* #var int
*
* #ORM\Column(name="status", type="integer")
*/
private $status;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
* #ORM\OneToMany(targetEntity="SupportMessages", mappedBy="thread")
*/
protected $messages;
public function __construct()
{
$this->messages = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
function getMessages() {
return $this->messages;
}
function setMessages($messages) {
$this->messages = $messages;
}
/**
* Set userId
*
* #param integer $userId
*
* #return SupportMessagesThreads
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get userId
*
* #return int
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set recipient
*
* #param integer $recipient
*
* #return SupportMessagesThreads
*/
public function setRecipient($recipient)
{
$this->recipient = $recipient;
return $this;
}
/**
* Get recipient
*
* #return int
*/
public function getRecipient()
{
return $this->recipient;
}
/**
* Set title
*
* #param string $title
*
* #return SupportMessagesThreads
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set status
*
* #param integer $status
*
* #return SupportMessagesThreads
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return int
*/
public function getStatus()
{
return $this->status;
}
/**
* Set created
*
* #param \DateTime $created
*
* #return SupportMessagesThreads
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
}
In My Controller i have This code:
$supportMessageThread = new SupportMessagesThreads();
$supportMessageThread
->setUserId($this->getUser()->getId())
->setStatus(0)
->setTitle($formData->getTitle())
->setRecipient($formData->getRecipient())
->setCreated(new \DateTime());
$supportMessage = new SupportMessages($formData);
$supportMessage
->setThreadId($supportMessageThread)
->setCreated(new \DateTime())
->setIsReadSender(1)
->setIsReadRecipient(0)
->setSender($this->getUser()->getId())
->setContent($formData->message);
$em = $this->getDoctrine()->getManager();
$em->persist($supportMessageThread);
$em->persist($supportMessage);
$em->flush();
My field called in #ORM\JoinColum name returns null every time. When i change "thread_id" to other fields ex. "sender" then "sender" field is null. What i can do to set id of SupportMessageThread entity to thread_id.
Printing data works fine. When i put test records to base manually and the next im get it by doctrine - everything is ok. The problem only occurs when save.
Please Help Me :((
Probably you want to use Cascade operations
And your mapping looks a bit weird. Note that you declare the argument as integer
/**
* Set threadId
*
* #param integer $threadId
*
* #return SupportMessages
*/
public function setThreadId($thread_id)
{
$this->thread_id = $thread_id;
return $this;
}
But SupportMessagesThreads is passed:
->setThreadId($supportMessageThread)
You should use objects instead scalars like
/**
* Set thread
*
* #param SupportMessagesThreads $thread
*
* #return SupportMessages
*/
public function setThread(SupportMessagesThreads $thread)
{
$this->thread = $thread;
return $this;
}
and remove $thread_id field from SupportMessagesThreads
In my case i had incorrect definitions of inversed and mapped by.
In both cases it was the same field todo.
That's the same case in the question above.
After changes it's
/**
* #ORM\OneToMany(targetEntity=MyTodoElement::class, mappedBy="myTodo")
*/
private $myTodoElement;
/**
* #ORM\ManyToOne(targetEntity=MyTodo::class, inversedBy="myTodoElement")
* #ORM\JoinColumn(nullable=false)
*/
private $myTodo;
I have two entities Categorie and ChampCat with ManyToMany relation and I want to get list of categories with related ChampCat by using doctrine QueryBuilder so I have used this query:
class CategorieRepository extends \Doctrine\ORM\EntityRepository
{
public function myFindCategories(array $tab){
$em = $this->getEntityManager();
$query = $em->select(array('cat', 'ch'))
->from('AnnonceBundle\Entity\Categorie', 'cat')
->join('cat.champsCat', 'ch')
->where('cat.id In (:tabOfIds)')
->setParameter('tabOfIds', array_values($tab))
->getQuery();
return $query->getResult();
}
}
Here u can see the Categorie Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Categorie
*
* #ORM\Table(name="categorie")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\CategorieRepository")
*/
class Categorie implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="refCat", type="string", length=100)
*/
private $refCat;
/**
* #var string
*
* #ORM\Column(name="libelleCat", type="string", length=50)
*/
private $libelleCat;
/**
* #ORM\ManyToMany(targetEntity="AnnonceBundle\Entity\ChampCat",cascade={"persist"})
*/
private $champsCat;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set refCat
*
* #param string $refCat
*
* #return Categorie
*/
public function setRefCat($refCat)
{
$this->refCat = $refCat;
return $this;
}
/**
* Get refCat
*
* #return string
*/
public function getRefCat()
{
return $this->refCat;
}
/**
* Set libelleCat
*
* #param string $libelleCat
*
* #return Categorie
*/
public function setLibelleCat($libelleCat)
{
$this->libelleCat = $libelleCat;
return $this;
}
/**
* Get libelleCat
*
* #return string
*/
public function getLibelleCat()
{
return $this->libelleCat;
}
/**
* Set champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function setChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat = null)
{
$this->champsCat = $champsCat;
return $this;
}
/**
* Get champsCat
*
* #return \AnnonceBundle\Entity\ChampCat
*/
public function getChampsCat()
{
return $this->champsCat;
}
/**
* Constructor
*/
public function __construct()
{
$this->champsCat = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*
* #return Categorie
*/
public function addChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat[] = $champsCat;
return $this;
}
/**
* Remove champsCat
*
* #param \AnnonceBundle\Entity\ChampCat $champsCat
*/
public function removeChampsCat(\AnnonceBundle\Entity\ChampCat $champsCat)
{
$this->champsCat->removeElement($champsCat);
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
And this is ChamCat Entity:
<?php
namespace AnnonceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ChampCat
*
* #ORM\Table(name="champ_cat")
* #ORM\Entity(repositoryClass="AnnonceBundle\Repository\ChampCatRepository")
*/
class ChampCat implements \JsonSerializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*#var string
*
* #ORM\Column(name="refCh", type="string")
*/
private $refCh;
/**
* #var string
*
* #ORM\Column(name="nom_ch", type="string", length=255)
*/
private $nomCh;
/**
* #var bool
*
* #ORM\Column(name="app_ch", type="boolean")
*/
private $appCh;
/**
* #var string
*
* #ORM\Column(name="format_ch", type="string", length=255)
*/
private $formatCh;
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->refCh;
}
/**
* Set refCh
*
* #param integer $refCh
* #return ChampCat
*/
public function setRefCh($refCh)
{
$this->refCh = $refCh;
return $this;
}
/**
* Get refCh
*
* #return integer
*/
public function getRefCh()
{
return $this->refCh;
}
/**
* Set nomCh
*
* #param string $nomCh
* #return ChampCat
*/
public function setNomCh($nomCh)
{
$this->nomCh = $nomCh;
return $this;
}
/**
* Get nomCh
*
* #return string
*/
public function getNomCh()
{
return $this->nomCh;
}
/**
* Set appCh
*
* #param boolean $appCh
* #return ChampCat
*/
public function setAppCh($appCh)
{
$this->appCh = $appCh;
return $this;
}
/**
* Get appCh
*
* #return boolean
*/
public function getAppCh()
{
return $this->appCh;
}
/**
* Set formatCh
*
* #param string $formatCh
* #return ChampCat
*/
public function setFormatCh($formatCh)
{
$this->formatCh = $formatCh;
return $this;
}
/**
* Get formatCh
*
* #return string
*/
public function getFormatCh()
{
return $this->formatCh;
}
function jsonSerialize()
{
return get_object_vars($this);
}
}
Unfortunately this query didn't work, so what am I missing ?
Is it working with this syntax?
public function myFindCategories(array $tab){
if(count($tab) == 0) return []; //or IN() will bug with an empty array
$query = $this->createQueryBuilder('cat')
->addSelect('ch')
->innerJoin('cat.champsCat', 'ch')
->where('cat.id in (:tabOfIds)')
->setParameter('tabOfIds', $tab)
->getQuery();
return $query->getResult();
}
I have a new problem related to Doctrine2 and Oracle...
I migrated an application from Symfony1 to symfony2. When I insert a new entry in the production database with Doctrine2, I get the error "ORA-00001: unique constraint violated". It tries to insert with the ID 1, if I try again it tries to insert with ID 2 etc...
Here is how I setup my entity :
<?php
namespace EspaceApprenti\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* ApprenticeMark
*
* #ORM\Table(name="APPRENTICE_MARK", indexes={#ORM\Index(name="IDX_8582BCF7105754FC", columns={"FK_BRANCH"}), #ORM\Index(name="IDX_8582BCF7C9387C17", columns={"FK_YEAR"}), #ORM\Index(name="IDX_8582BCF73B451C64", columns={"FK_MARKTYPE"})})
* #ORM\Entity(repositoryClass="EspaceApprenti\UserBundle\Entity\ApprenticeMarkRepository")
*/
class ApprenticeMark
{
/**
* #var integer
*
* #ORM\Column(name="COEFFICIENT", type="bigint", nullable=false)
*/
private $coefficient;
/**
* #var integer
*
* #ORM\Column(name="ID", type="bigint", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="RESULT", type="decimal", precision=2, scale=1, nullable=false)
*/
private $result;
/**
* #var \ApprenticeBranch
*
* #ORM\ManyToOne(targetEntity="ApprenticeBranch")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_BRANCH", referencedColumnName="ID")
* })
*/
private $fkBranch;
/**
* #var \ApprenticeYear
*
* #ORM\ManyToOne(targetEntity="ApprenticeYear")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_YEAR", referencedColumnName="ID", onDelete="CASCADE")
* })
*/
private $fkYear;
/**
* #var \ApprenticeMarktype
*
* #ORM\ManyToOne(targetEntity="ApprenticeMarktype")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="FK_MARKTYPE", referencedColumnName="ID")
* })
*/
private $fkMarktype;
/**
* Set coefficient
*
* #param integer $coefficient
* #return ApprenticeMark
*/
public function setCoefficient($coefficient)
{
$this->coefficient = $coefficient;
return $this;
}
/**
* Get coefficient
*
* #return integer
*/
public function getCoefficient()
{
return $this->coefficient;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set result
*
* #param integer $result
* #return ApprenticeMark
*/
public function setResult($result)
{
$this->result = $result;
return $this;
}
/**
* Get result
*
* #return integer
*/
public function getResult()
{
return $this->result;
}
/**
* Set fkBranch
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeBranch $fkBranch
* #return ApprenticeMark
*/
public function setFkBranch(\EspaceApprenti\UserBundle\Entity\ApprenticeBranch $fkBranch = null)
{
$this->fkBranch = $fkBranch;
return $this;
}
/**
* Get fkBranch
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeBranch
*/
public function getFkBranch()
{
return $this->fkBranch;
}
/**
* Set fkYear
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeYear $fkYear
* #return ApprenticeMark
*/
public function setFkYear(\EspaceApprenti\UserBundle\Entity\ApprenticeYear $fkYear = null)
{
$this->fkYear = $fkYear;
return $this;
}
/**
* Get fkYear
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeYear
*/
public function getFkYear()
{
return $this->fkYear;
}
/**
* Set fkMarktype
*
* #param \EspaceApprenti\UserBundle\Entity\ApprenticeMarktype $fkMarktype
* #return ApprenticeMark
*/
public function setFkMarktype(\EspaceApprenti\UserBundle\Entity\ApprenticeMarktype $fkMarktype = null)
{
$this->fkMarktype = $fkMarktype;
return $this;
}
/**
* Get fkMarktype
*
* #return \EspaceApprenti\UserBundle\Entity\ApprenticeMarktype
*/
public function getFkMarktype()
{
return $this->fkMarktype;
}
}
Here is the code of the controller :
public function newAction($idYear,$idYeartype)
{
$m = $this->getDoctrine()
->getManager();
// Get year
$year = $m->getRepository('EspaceApprentiUserBundle:ApprenticeYear')->find($idYear);
if (!$year) {
throw $this->createNotFoundException('Year not found');
}
// Get yeartype
$yeartype = $m->getRepository('EspaceApprentiUserBundle:ApprenticeYeartype')->find($idYeartype);
if (!$yeartype) {
throw $this->createNotFoundException('Year type not found');
}
// Get apprentice
$apprentice = $m->getRepository('EspaceApprentiUserBundle:ApprenticeApprentice')->find($year->getFkApprentice()->getId());
if (!$apprentice) {
throw $this->createNotFoundException('Apprentice type not found');
}
$mark = new ApprenticeMark();
$mark->setFkYear($year);
$form = $this->createForm(new ApprenticeMarkType($yeartype), $mark);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$m->persist($mark);
$m->flush();
return $this->redirect($this->generateUrl('grids_apprentice_index',array('idApprentice' => $apprentice->getId())));
}
}
return $this->render('EspaceApprentiGridsBundle:Grids_Mark:new.html.twig', array('apprentice' => $apprentice, 'form' => $form->createView()));
}
How do I configure Doctrine2 to get the last ID and not just increment from 1 ?
Or should I get and insert the last ID manually ?
Regards
I found the solution to my problem. Apparently my SEQUENCES in Oracle were not up to date, so I had to manually update them.
I am using Symfony2 with Doctrine and when I query from my controller the next error appears(it appears in the navigator when I call for the page):
Entity class 'Bdreamers\SuenoBundle\Entity\Sueno_video' used in the discriminator map of class 'Bdreamers\SuenoBundle\Entity\Sueno' does not exist.
I have one entity(superclass) called "Sueno" and two entities that extend from it(subclasses): Sueno_foto and Sueno_video.
When I load the fixtures, Doctrine works perfectly and fills the database without any issue, filling correctly the discriminator field "tipo" in the "Sueno" table. It also fills correctly the inherited entity table "Sueno_video" introducing the ID of "Sueno" and the exclusive fields of "Sueno_video"
This is the code of the entity file for "Sueno":
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
* #ORM\InheritanceType("JOINED")
* #ORM\DiscriminatorColumn(name="tipo", type="string")
* #ORM\DiscriminatorMap({"sueno" = "Sueno", "video" = "Sueno_video", "foto" = "Sueno_foto"})
*/
class Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario")
**/
private $usuario;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\SuenoBundle\Entity\Tag", inversedBy="suenos")
* #ORM\JoinTable(name="suenos_tags")
**/
private $tags;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_sigue")
* #ORM\JoinTable(name="usuarios_siguen")
**/
private $usuariosSeguidores;
/**
* #ORM\ManyToMany(targetEntity="Bdreamers\UsuarioBundle\Entity\Usuario", mappedBy="suenos_colabora")
* #ORM\JoinTable(name="usuarios_colaboran")
**/
private $usuariosColaboradores;
/**
* #var \DateTime
*
* #ORM\Column(name="fecha_subida", type="datetime")
*/
private $fechaSubida;
/**
* #var string
*
* #ORM\Column(name="titulo", type="string", length=40)
*/
private $titulo;
/**
* #var string
*
* #ORM\Column(name="que_pido", type="string", length=140)
*/
private $quePido;
/**
* #var string
*
* #ORM\Column(name="texto", type="string", length=540)
*/
private $texto;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set usuario
*
* #param string $usuario
* #return Sueno
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
return $this;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
public function getTags()
{
return $this->tags;
}
/**
* Set usuariosSeguidores
*
* #param string $usuariosSeguidores
* #return Sueno
*/
public function setUsuariosSeguidores($usuariosSeguidores)
{
$this->usuariosSeguidores = $usuariosSeguidores;
return $this;
}
/**
* Get usuariosSeguidores
*
* #return string
*/
public function getUsuariosSeguidores()
{
return $this->usuariosSeguidores;
}
/**
* Set usuariosColaboradores
*
* #param string $usuariosColaboradores
* #return Sueno
*/
public function setUsuariosColaboradores($usuariosColaboradores)
{
$this->usuariosColaboradores = $usuariosColaboradores;
return $this;
}
/**
* Get usuariosColaboradores
*
* #return string
*/
public function getUsuariosColaboradores()
{
return $this->usuariosColaboradores;
}
/**
* Set fechaSubida
*
* #param \DateTime $fechaSubida
* #return Sueno
*/
public function setFechaSubida($fechaSubida)
{
$this->fechaSubida = $fechaSubida;
return $this;
}
/**
* Get fechaSubida
*
* #return \DateTime
*/
public function getFechaSubida()
{
return $this->fechaSubida;
}
/**
* Set titulo
*
* #param string $titulo
* #return Sueno
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set quePido
*
* #param string $quePido
* #return Sueno
*/
public function setQuePido($quePido)
{
$this->quePido = $quePido;
return $this;
}
/**
* Get quePido
*
* #return string
*/
public function getQuePido()
{
return $this->quePido;
}
/**
* Set texto
*
* #param string $texto
* #return Sueno
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
public function __construct() {
$this->usuariosColaboradores = new \Doctrine\Common\Collections\ArrayCollection();
$this->usuariosSeguidores = new \Doctrine\Common\Collections\ArrayCollection();
$this->tags = new \Doctrine\Common\Collections\ArrayCollection();
}
public function __toString()
{
return $this->getTitulo();
}
}
And this is the code for the entity Sueno_video:
<?php
namespace Bdreamers\SuenoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\Entity
*/
class Sueno_video extends Sueno
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="link_video", type="string", length=255)
*/
private $linkVideo;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set linkVideo
*
* #param string $linkVideo
* #return Sueno_video
*/
public function setLinkVideo($linkVideo)
{
$this->linkVideo = $linkVideo;
return $this;
}
/**
* Get linkVideo
*
* #return string
*/
public function getLinkVideo()
{
return $this->linkVideo;
}
}
And finally the code in the controller:
public function homeAction()
{
$em = $this->getDoctrine()->getManager();
$suenos = $em->getRepository('SuenoBundle:Sueno')->findOneBy(array(
'fechaSubida' => new \DateTime('now -2 days')
));
return $this->render('EstructuraBundle:Home:home_registrado.html.twig');
}
The autoloader won't be able to resolve those class names to file paths, hence why it can't find your classes.
Changing the file and class names to SuenoVideo and SuenoFoto.