In symfony2 when I insert data into to database I receive an exception:
An exception occurred while executing 'INSERT INTO practice_user (user_id, practice_id, practice_text, type_id) VALUES (?, ?, ?, ?)' with params [null, "1", "test", 2]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
PracticeUser.php:
<?php
namespace fl\PracticeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="practice_user")
*/
class PracticeUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $submit_practice_id;
/**
* #ORM\Column(type="integer")
*/
protected $user_id;
/**
* #ORM\Column(type="integer")
*/
protected $practice_id;
/**
* #ORM\Column(type="text")
*/
protected $practice_text;
/**
* #ORM\Column(type="integer")
*/
protected $type_id;
//many-to-one fos_user
/**
* #ORM\ManyToOne(targetEntity="fl\UserBundle\Entity\User", inversedBy="practices")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE", nullable=false))
*/
protected $user;
/**
* Get submit_practice_id
*
* #return integer
*/
public function getSubmitPracticeId()
{
return $this->submit_practice_id;
}
/**
* Set user_id
*
* #param integer $userId
* #return PracticeUser
*/
public function setUserId($userId)
{
$this->user_id = $userId;
return $this;
}
/**
* Get user_id
*
* #return integer
*/
public function getUserId()
{
return $this->user_id;
}
/**
* Set practice_id
*
* #param integer $practiceId
* #return PracticeUser
*/
public function setPracticeId($practiceId)
{
$this->practice_id = $practiceId;
return $this;
}
/**
* Get practice_id
*
* #return integer
*/
public function getPracticeId()
{
return $this->practice_id;
}
/**
* Set practice_text
*
* #param string $practiceText
* #return PracticeUser
*/
public function setPracticeText($practiceText)
{
$this->practice_text = $practiceText;
return $this;
}
/**
* Get practice_text
*
* #return string
*/
public function getPracticeText()
{
return $this->practice_text;
}
/**
* Set type_id
*
* #param integer $typeId
* #return PracticeUser
*/
public function setTypeId($typeId)
{
$this->type_id = $typeId;
return $this;
}
/**
* Get type_id
*
* #return integer
*/
public function getTypeId()
{
return $this->type_id;
}
/**
* Set user
*
* #param \fl\UserBundle\Entity\User $user
* #return PracticeUser
*/
public function setUser(\fl\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return \fl\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
User.php
<?php
namespace fl\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
//one-to-one user_detail
/**
* #ORM\OneToOne(targetEntity="fl\UserBundle\Entity\UserDetail", mappedBy="user")
*/
protected $user_detail;
//one-to-one account
/**
* #ORM\OneToOne(targetEntity="fl\UserBundle\Entity\Account", mappedBy="user")
*/
protected $account;
//one-to-many language_user
/**
* #ORM\OneToMany(targetEntity="fl\UserBundle\Entity\LanguageUser", mappedBy="user")
*/
protected $languageusers;
//one-to-many practice_user
/**
* #ORM\OneToMany(targetEntity="fl\PracticeBundle\Entity\PracticeUser", mappedBy="user")
*/
protected $practices;
//one-to-many practice_review
/**
* #ORM\OneToMany(targetEntity="fl\PracticeBundle\Entity\PracticeReview", mappedBy="user")
*/
protected $reviews;
public function __construct()
{
parent::__construct();
// your own logic
//one to many with language_user table
$this->languageusers = new ArrayCollection();
//one-to-many practice_user
$this->practices = new ArrayCollection();
//one-to-many practice_review
$this->reviews = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user_detail
*
* #param \fl\UserBundle\Entity\UserDetail $userDetail
* #return User
*/
public function setUserDetail(\fl\UserBundle\Entity\UserDetail $userDetail = null)
{
$this->user_detail = $userDetail;
return $this;
}
/**
* Get user_detail
*
* #return \fl\UserBundle\Entity\UserDetail
*/
public function getUserDetail()
{
return $this->user_detail;
}
/**
* Set account
*
* #param \fl\UserBundle\Entity\Account $account
* #return User
*/
public function setAccount(\fl\UserBundle\Entity\Account $account = null)
{
$this->account = $account;
return $this;
}
/**
* Get account
*
* #return \fl\UserBundle\Entity\Account
*/
public function getAccount()
{
return $this->account;
}
/**
* Add languageusers
*
* #param \fl\UserBundle\Entity\LanguageUser $languageusers
* #return User
*/
public function addLanguageuser(\fl\UserBundle\Entity\LanguageUser $languageusers)
{
$this->languageusers[] = $languageusers;
return $this;
}
/**
* Remove languageusers
*
* #param \fl\UserBundle\Entity\LanguageUser $languageusers
*/
public function removeLanguageuser(\fl\UserBundle\Entity\LanguageUser $languageusers)
{
$this->languageusers->removeElement($languageusers);
}
/**
* Get languageusers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getLanguageusers()
{
return $this->languageusers;
}
/**
* Add practices
*
* #param \fl\PracticeBundle\Entity\PracticeUser $practices
* #return User
*/
public function addPractice(\fl\PracticeBundle\Entity\PracticeUser $practices)
{
$this->practices[] = $practices;
return $this;
}
/**
* Remove practices
*
* #param \fl\PracticeBundle\Entity\PracticeUser $practices
*/
public function removePractice(\fl\PracticeBundle\Entity\PracticeUser $practices)
{
$this->practices->removeElement($practices);
}
/**
* Get practices
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPractices()
{
return $this->practices;
}
/**
* Add reviews
*
* #param \fl\PracticeBundle\Entity\PracticeReview $reviews
* #return User
*/
public function addReview(\fl\PracticeBundle\Entity\PracticeReview $reviews)
{
$this->reviews[] = $reviews;
return $this;
}
/**
* Remove reviews
*
* #param \fl\PracticeBundle\Entity\PracticeReview $reviews
*/
public function removeReview(\fl\PracticeBundle\Entity\PracticeReview $reviews)
{
$this->reviews->removeElement($reviews);
}
/**
* Get reviews
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getReviews()
{
return $this->reviews;
}
}
code when I try insert to the DataBase:
$user_id = $user->getId();
$submit_dictation = new PracticeUser();
$submit_dictation->setUserId($user_id);
$submit_dictation->setPracticeId($dictation_id);
$submit_dictation->setPracticeText($get_user_answer);
$submit_dictation->setTypeId(self::PRACTICE_DICTATION);
$em = $this->getDoctrine()->getManager();
$em->persist($submit_dictation);
$em->flush();
I also checked(with var_dump)the variable $user_id but is not null, I receive the user id.
Thanks in advance
You don't need $user_id, as FuzzyTree told you, but you need to fill the $user attribute by adding $submit_dictation->setUser($user) instead of $submit_dictation->setUserId($user->getId()) when you insert in the database.
This is why, among other things, Doctrine is useful, you don't need to understant how relations work : you don't need to give an id but just the entity itself.
Related
I've been struggling with doing a multiple join in DQL.
Here is my code:
$query = $em->createQuery(
'SELECT k
FROM AppBundle:Keyword k
JOIN k.company c
JOIN k.entry e
WHERE c.user = :id
ORDER BY k.name ASC'
)->setParameter('id',$user_id);
But it gives me "Notice: Undefined index: entry", when executing it.
Here is my keyword entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Keyword
*/
class Keyword
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $name;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Keyword
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $user;
/**
* Constructor
*/
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add user
*
* #param \AppBundle\Entity\User $user
* #return Keyword
*/
public function addUser(\AppBundle\Entity\User $user)
{
$this->user[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AppBundle\Entity\User $user
*/
public function removeUser(\AppBundle\Entity\User $user)
{
$this->user->removeElement($user);
}
/**
* Get user
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
/**
* Set user
*
* #param \AppBundle\Entity\User $user
* #return Keyword
*/
public function setUser(\AppBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $company;
/**
* Add company
*
* #param \AppBundle\Entity\Company $company
* #return Keyword
*/
public function addCompany(\AppBundle\Entity\Company $company)
{
$this->company[] = $company;
return $this;
}
/**
* Remove company
*
* #param \AppBundle\Entity\Company $company
*/
public function removeCompany(\AppBundle\Entity\Company $company)
{
$this->company->removeElement($company);
}
/**
* Get company
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCompany()
{
return $this->company;
}
/**
* Set company
*
* #param \AppBundle\Entity\Company $company
* #return Keyword
*/
public function setCompany(\AppBundle\Entity\Company $company = null)
{
$this->company = $company;
return $this;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $entry;
/**
* Add entry
*
* #param \AppBundle\Entity\Entry $entry
* #return Keyword
*/
public function addEntry(\AppBundle\Entity\Entry $entry)
{
$this->entry[] = $entry;
return $this;
}
/**
* Remove entry
*
* #param \AppBundle\Entity\Entry $entry
*/
public function removeEntry(\AppBundle\Entity\Entry $entry)
{
$this->entry->removeElement($entry);
}
/**
* Get entry
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getEntry()
{
return $this->entry;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $ranking;
/**
* Add ranking
*
* #param \AppBundle\Entity\Ranking $ranking
* #return Keyword
*/
public function addRanking(\AppBundle\Entity\Ranking $ranking)
{
$this->ranking[] = $ranking;
return $this;
}
/**
* Remove ranking
*
* #param \AppBundle\Entity\Ranking $ranking
*/
public function removeRanking(\AppBundle\Entity\Ranking $ranking)
{
$this->ranking->removeElement($ranking);
}
/**
* Get ranking
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRanking()
{
return $this->ranking;
}
}
And my entry entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Entry
*/
class Entry
{
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $path;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* #param string $path
* #return Entry
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* #var \AppBundle\Entity\Keyword
*/
private $keyword;
/**
* Set keyword
*
* #param \AppBundle\Entity\Keyword $keyword
* #return Entry
*/
public function setKeyword(\AppBundle\Entity\Keyword $keyword = null)
{
$this->keyword = $keyword;
return $this;
}
/**
* Get keyword
*
* #return \AppBundle\Entity\Keyword
*/
public function getKeyword()
{
return $this->keyword;
}
/**
* #var \Doctrine\Common\Collections\Collection
*/
private $ranking;
/**
* Constructor
*/
public function __construct()
{
$this->ranking = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add ranking
*
* #param \AppBundle\Entity\Ranking $ranking
* #return Entry
*/
public function addRanking(\AppBundle\Entity\Ranking $ranking)
{
$this->ranking[] = $ranking;
return $this;
}
/**
* Remove ranking
*
* #param \AppBundle\Entity\Ranking $ranking
*/
public function removeRanking(\AppBundle\Entity\Ranking $ranking)
{
$this->ranking->removeElement($ranking);
}
/**
* Get ranking
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getRanking()
{
return $this->ranking;
}
}
Btw I'm pretty new with symfony and doctrine.
I appreciate all kinds of help!
You need to provide mapping information for each attribute in your model class as well as provide the Entity mapping for the class. Take a look at http://doctrine-common.readthedocs.org/en/latest/reference/annotations.html
Each of your model classes need the #ORM\Entity annotation to tell doctrine it is a mapped entity. So for your case you would have:
/**
* Entry
* #ORM\Entity
*/
class Entry
{
...
Then each attribute you want to be mapped to the database needs an #ORM\Column annotation. For example:
/**
* #var integer
* #ORM\Id #ORM\Column #ORM\GeneratedValue
*/
private $id;
/**
* #var string
* #ORM\Column(type="string")
*/
private $path;
Then you need to create relationship mapping annotations for any relationships between your models (Keyword -> Company, Keyword -> Entry etc), using one of the mappings on here http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html
Once you have all the correct mappings use the command line tool app/console doctrine:schema:update to make sure your model is in sync with your database.
Your DQL seems fine so once you have the correct mappings in place you might have better luck.
in my test project I have 2 entities :
- endUser (extend of FOSUserBundle)
- Rezo (will containt approved relation between two members)
the both entities have been defined as :
EndUser Entity :
<?php
namespace Core\CustomerBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* EndUser
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
*/
class EndUser extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
* #ORM\Column(name="firstname", type="string", length=255)
*/
private $firstname;
/**
* #var string
* #ORM\Column(name="lastname", type="string", length=255)
*/
private $lastname;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaissance", type="datetime", nullable=true)
*/
private $DateNaissance;
/**
* #ORM\OneToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"persist", "merge", "remove"})
* #ORM\JoinColumn(name="adressbook_id", referencedColumnName="id", nullable=true)
*/
private $adressbook;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Discipline", mappedBy="endusers")
*/
private $disciplines;
/**
* #ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Experiences", mappedBy="endusers")
*/
private $experiences;
/**
* #var string
* #ORM\Column(name="avatar", type="string", length=255, nullable=true)
*/
private $avatar;
/**
* #var string
* #ORM\Column(name="repository", type="string", length=255, nullable=true)
*/
private $repository;
/**
* #ORM\OneToMany(targetEntity="Core\MyEquiBookBundle\Entity\NiveauEndUser", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $niveaux;
/**
* #ORM\OneToMany(targetEntity="Core\GeneralBundle\Entity\Rezo", mappedBy="enduser", cascade={"remove", "persist"})
*/
protected $friends;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->disciplines = new \Doctrine\Common\Collections\ArrayCollection();
$this->niveaux = new \Doctrine\Common\Collections\ArrayCollection();
$this->experiences = new \Doctrine\Common\Collections\ArrayCollection();
$this->friends = new \Doctrine\Common\Collections\ArrayCollection();
$this->expiresAt = new \DateTime("+1 year");
$this->credentialsExpireAt = new \DateTime("+1 year");
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set avatar
*
* #param string $avatar
* #return EndUser
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set repository
*
* #param string $repository
* #return EndUser
*/
public function setRepository($repository)
{
$this->repository = $repository;
return $this;
}
/**
* Get repository
*
* #return string
*/
public function getRepository()
{
return $this->repository;
}
/**
* Set adressbook
*
* #param \Core\CustomerBundle\Entity\EndUser $adressbook
* #return EndUser
*/
public function setAdressbook(\Core\CustomerBundle\Entity\EndUser $adressbook = null)
{
$this->adressbook = $adressbook;
return $this;
}
/**
* Get adressbook
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getAdressbook()
{
return $this->adressbook;
}
/**
* Add disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
* #return EndUser
*/
public function addDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines[] = $disciplines;
return $this;
}
/**
* Remove disciplines
*
* #param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
*/
public function removeDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
{
$this->disciplines->removeElement($disciplines);
}
/**
* Get disciplines
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getDisciplines()
{
return $this->disciplines;
}
/**
* Add niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
* #return EndUser
*/
public function addNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux[] = $niveaux;
return $this;
}
/**
* Remove niveaux
*
* #param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
*/
public function removeNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
{
$this->niveaux->removeElement($niveaux);
}
/**
* Get niveaux
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getNiveaux()
{
return $this->niveaux;
}
/**
* Add experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
* #return EndUser
*/
public function addExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences[] = $experiences;
return $this;
}
/**
* Remove experiences
*
* #param \Core\MyEquiBookBundle\Entity\Experiences $experiences
*/
public function removeExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
{
$this->experiences->removeElement($experiences);
}
/**
* Get experiences
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getExperiences()
{
return $this->experiences;
}
/**
* Add friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
* #return EndUser
*/
public function addFriend(\Core\GeneralBundle\Entity\Rezo $friends )
{
$this->friends[] = $friends;
return $this;
}
/**
* Remove friends
*
* #param \Core\GeneralBundle\Entity\Rezo $friends
*/
public function removeFriend(\Core\GeneralBundle\Entity\Rezo $friends)
{
$this->friends->removeElement($friends);
}
/**
* Get friends
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFriends()
{
return $this->friends;
}
/**
* Set firstname
*
* #param string $firstname
* #return EndUser
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set lastname
*
* #param string $lastname
* #return EndUser
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* #return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set DateNaissance
*
* #param \DateTime $dateNaissance
* #return EndUser
*/
public function setDateNaissance($dateNaissance)
{
$this->DateNaissance = $dateNaissance;
return $this;
}
/**
* Get DateNaissance
*
* #return \DateTime
*/
public function getDateNaissance()
{
return $this->DateNaissance;
}
}
Rezo Entity :
<?php
namespace Core\GeneralBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Rezo
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Core\GeneralBundle\Entity\RezoRepository")
*/
class Rezo
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="RequestedDate", type="datetime")
*/
private $requestedDate;
/**
* #var \DateTime
*
* #ORM\Column(name="AcceptedDate", type="datetime", nullable=true)
*/
private $acceptedDate;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\Enduser", inversedBy="friends", cascade={"refresh"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $enduser;
/**
* #ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"refresh"})
* #ORM\JoinColumn(name="friendwith", referencedColumnName="id")
*/
protected $friendwith;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set requestedDate
*
* #param \DateTime $requestedDate
* #return Rezo
*/
public function setRequestedDate($requestedDate)
{
$this->requestedDate = $requestedDate;
return $this;
}
/**
* Get requestedDate
*
* #return \DateTime
*/
public function getRequestedDate()
{
return $this->requestedDate;
}
/**
* Set acceptedDate
*
* #param \DateTime $acceptedDate
* #return Rezo
*/
public function setAcceptedDate($acceptedDate)
{
$this->acceptedDate = $acceptedDate;
return $this;
}
/**
* Get acceptedDate
*
* #return \DateTime
*/
public function getAcceptedDate()
{
return $this->acceptedDate;
}
/**
* Set enduser
*
* #param \Core\CustomerBundle\Entity\EndUser $enduser
* #return Rezo
*/
public function setEnduser(\Core\CustomerBundle\Entity\EndUser $enduser = null)
{
$this->enduser = $enduser;
return $this;
}
/**
* Get enduser
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getEnduser()
{
return $this->enduser;
}
/**
* Set friendwith
*
* #param \Core\CustomerBundle\Entity\EndUser $friendwith
* #return Rezo
*/
public function setFriendwith(\Core\CustomerBundle\Entity\EndUser $friendwith = null)
{
$this->friendwith = $friendwith;
return $this;
}
/**
* Get friendwith
*
* #return \Core\CustomerBundle\Entity\EndUser
*/
public function getFriendwith()
{
return $this->friendwith;
}
when I run :
app/console doctrine:schema:update --force
The following MySQL table has been created :
CREATE TABLE IF NOT EXISTS `Rezo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`friendwith` int(11) DEFAULT NULL,
`RequestedDate` datetime NOT NULL,
`AcceptedDate` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_681FC4BA76ED395` (`user_id`),
KEY `IDX_681FC4B1094AD75` (`friendwith`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
In the RezoController.php controller I would like to give to endUser opportunity to accept a contact request fot this I have created a function named : acceptnewrequestAction($id)
public function acceptnewrequestAction($id){
$em = $this->getDoctrine()->getManager();
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->find($id);
$user1 = $rezo->getEnduser();
$user2 = $rezo->getFriendwith();
$dateRequest = $rezo->getRequestedDate();
$rezo->setAcceptedDate(new \DateTime('now'));
$em->persist($rezo);
$em->flush();
/* check if inverse relation exist */
$query = $em->CreateQuerybuilder();
$query->select('t0.id');
$query->from('CoreGeneralBundle:Rezo','t0');
$query->where('t0.acceptedDate IS NULL');
$query->andWhere('t0.enduser = :userId');
$query->andWhere('t0.friendwith =:userId2');
$query->SetParameters(array('userId'=> $user2, 'userId2'=>$user1));
$result = $query->getQuery()->getOneOrNullResult();
if ( is_object($result))
{
$rezo = $em->getRepository('CoreGeneralBundle:Rezo')->findById($result->getId());
$rezo->setAcceptedDate(new \DateTime('now'));
} else {
$rezo = new Rezo();
$rezo->setRequestedDate(new \Datetime('now'));
$rezo->setAcceptedDate(new \DateTime('now'));
$rezo->Setenduser($user2);
$rezo->setFriendwith($user1);
}
$em->persist($rezo);
$em->flush();
return $this->render(controller('CoreGeneralBundle:Rezo:RezoList'));
}
I would like to know how I can use results to know if one object if found or return is Null and in case it exists update it or create a new one.
thank you for your help
getOneOrNullResult method tells you if any record in database is found, or not.
If it return null, it means that you have some results, and in your case you have to insert new one.
But when it exists some records, this method will return object instance of your entity. That means in your case you have to update existing record.
Please remember, that getOneOrNullResult method throws exception, when result set is not unique.
I have a Property:
(Note: the legacy_id was not my doing and is now ingrained in the app so can't be changed at this time)
<?php
namespace Entity\Beaverusiv;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Entity\Beaverusiv\Property
*
* #ORM\Entity()
* #ORM\Table(name="properties", indexes={#ORM\Index(name="fk_properties_smoking_options1_idx", columns={"smoking_id"}), #ORM\Index(name="fk_properties_linen_options1_idx", columns={"linen_id"}), #ORM\Index(name="fk_properties_pets_options1_idx", columns={"pets_id"}), #ORM\Index(name="fk_properties_property_city1_idx", columns={"city_id"})})
*/
class Property
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $id;
/**
* #ORM\Column(type="integer")
*/
protected $legacy_id;
/**
* #ORM\ManyToMany(targetEntity="FeaturesOption", mappedBy="properties")
*/
protected $featuresOptions;
public function __construct()
{
$this->featuresOptions = new ArrayCollection();
}
/**
* Set the value of id.
*
* #param integer $id
* #return \Entity\Beaverusiv\Property
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get the value of id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of legacy_id.
*
* #param integer $legacy_id
* #return \Entity\Beaverusiv\Property
*/
public function setLegacyId($legacy_id)
{
$this->legacy_id = $legacy_id;
return $this;
}
/**
* Get the value of legacy_id.
*
* #return integer
*/
public function getLegacyId()
{
return $this->legacy_id;
}
/**
* Add FeaturesOption entity to collection.
*
* #param \Entity\Beaverusiv\FeaturesOption $featuresOption
* #return \Entity\Beaverusiv\Property
*/
public function addFeaturesOption(FeaturesOption $featuresOption)
{
$this->featuresOptions[] = $featuresOption;
return $this;
}
/**
* Get FeaturesOption entity collection.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getFeaturesOptions()
{
return $this->featuresOptions;
}
}
And FeaturesOption:
<?php
namespace Entity\Beaverusiv;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Entity\Beaverusiv\FeaturesOption
*
* #ORM\Entity()
* #ORM\Table(name="features_options")
*/
class FeaturesOption
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $display_order;
/**
* #ORM\Column(type="string", length=200, nullable=true)
*/
protected $text;
/**
* #ORM\Column(type="integer", nullable=true)
*/
protected $status;
/**
* #ORM\ManyToMany(targetEntity="Property", inversedBy="featuresOptions")
* #ORM\JoinTable(name="properties_features",
* joinColumns={#ORM\JoinColumn(name="feature_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="property_id", referencedColumnName="id")}
* )
*/
protected $properties;
public function __construct()
{
$this->properties = new ArrayCollection();
}
/**
* Set the value of id.
*
* #param integer $id
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get the value of id.
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of display_order.
*
* #param integer $display_order
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function setDisplayOrder($display_order)
{
$this->display_order = $display_order;
return $this;
}
/**
* Get the value of display_order.
*
* #return integer
*/
public function getDisplayOrder()
{
return $this->display_order;
}
/**
* Set the value of text.
*
* #param string $text
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function setText($text)
{
$this->text = $text;
return $this;
}
/**
* Get the value of text.
*
* #return string
*/
public function getText()
{
return $this->text;
}
/**
* Set the value of status.
*
* #param integer $status
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get the value of status.
*
* #return integer
*/
public function getStatus()
{
return $this->status;
}
/**
* Add Property entity to collection.
*
* #param \Entity\Beaverusiv\Property $property
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function addProperty(Property $property)
{
$property->addFeaturesOption($this);
$this->properties[] = $property;
return $this;
}
/**
* Get Property entity collection.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProperties()
{
return $this->properties;
}
}
And the pivot:
<?php
namespace Entity\Beaverusiv;
use Doctrine\ORM\Mapping as ORM;
/**
* Entity\Beaverusiv\PropertiesFeature
*
* #ORM\Entity()
* #ORM\Table(name="properties_features", indexes={#ORM\Index(name="fk_properties_features_features_options1_idx", columns={"feature_id"}), #ORM\Index(name="fk_properties_features_properties1_idx", columns={"property_id"})})
*/
class PropertiesFeature
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $feature_id;
/**
* #ORM\Id
* #ORM\Column(type="integer")
*/
protected $property_id;
/**
* #ORM\ManyToOne(targetEntity="FeaturesOption", inversedBy="propertiesFeatures")
* #ORM\JoinColumn(name="feature_id", referencedColumnName="id", nullable=false)
*/
protected $featuresOption;
/**
* #ORM\ManyToOne(targetEntity="Property", inversedBy="propertiesFeatures")
* #ORM\JoinColumn(name="property_id", referencedColumnName="id", nullable=false)
*/
protected $property;
public function __construct()
{
}
/**
* Set the value of feature_id.
*
* #param integer $feature_id
* #return \Entity\Beaverusiv\PropertiesFeature
*/
public function setFeatureId($feature_id)
{
$this->feature_id = $feature_id;
return $this;
}
/**
* Get the value of feature_id.
*
* #return integer
*/
public function getFeatureId()
{
return $this->feature_id;
}
/**
* Set the value of property_id.
*
* #param integer $property_id
* #return \Entity\Beaverusiv\PropertiesFeature
*/
public function setPropertyId($property_id)
{
$this->property_id = $property_id;
return $this;
}
/**
* Get the value of property_id.
*
* #return integer
*/
public function getPropertyId()
{
return $this->property_id;
}
/**
* Set FeaturesOption entity (many to one).
*
* #param \Entity\Beaverusiv\FeaturesOption $featuresOption
* #return \Entity\Beaverusiv\PropertiesFeature
*/
public function setFeaturesOption(FeaturesOption $featuresOption = null)
{
$this->featuresOption = $featuresOption;
$this->feature_id = $featuresOption->getId();
return $this;
}
/**
* Get FeaturesOption entity (many to one).
*
* #return \Entity\Beaverusiv\FeaturesOption
*/
public function getFeaturesOption()
{
return $this->featuresOption;
}
/**
* Set Property entity (many to one).
*
* #param \Entity\Beaverusiv\Property $property
* #return \Entity\Beaverusiv\PropertiesFeature
*/
public function setProperty(Property $property = null)
{
$this->property = $property;
$this->property_id = $property->getLegacyId();
return $this;
}
/**
* Get Property entity (many to one).
*
* #return \Entity\Beaverusiv\Property
*/
public function getProperty()
{
return $this->property;
}
}
I am having to bring in data from an older DB, like this:
<?php
public function sync()
{
$persist_count = 0; // Keep track of home many properties are ready to be flushed
$flush_count = 20; // Persist and flush the properties in groups of...
$i = 0;
$CI =& get_instance();
$legacy_properties = null;
while ($legacy_properties !== false)
{
$legacy_properties = $this->doctrine->mssql
->getRepository('Entity\MSSQL\TblProperty')
->getProperties($i, $flush_count);
if (count($legacy_properties)===0)
{
break;
}
foreach ($legacy_properties as $legacy_property)
{
// Legacy ID
$legacy_id = $legacy_property['propertyID'];
// Lets see if this property already exists in the new database. If it does, we'll just use that.
$property = $this->doctrine->em
->getRepository('Entity\Beaverusiv\Property')
->findOneBy(array(
'legacy_id' => $legacy_id
));
// If the property from the legacy database does not exist in the new database, let's add it.
if (! $property)
{
$property = new Entity\Beaverusiv\Property; // create a new property instance
$property->setLegacyId($legacy_id);
}
// Update property details
// Set all the other Property fields
$legacy_features = $this->doctrine->mssql
->getRepository('Entity\MSSQL\TblProperty')
->findOneBy(array('propertyID' => $legacy_id))
->getTblPropertyFeaturesJoins();
foreach ($legacy_features as $legacy_feature) {
$feature_id = $legacy_feature->getTblPropertyFeature()->getFeatureID();
$feature = $this->doctrine->em
->getRepository('Entity\Beaverusiv\FeaturesOption')
->findOneBy(array(
'id' => $feature_id
));
$feature_pivot = new Entity\Beaverusiv\PropertiesFeature;
$feature_pivot->setFeaturesOption($feature);
$feature_pivot->setProperty($property);
$this->doctrine->em->merge($feature_pivot);
}
// Persist this property, ready forz flushing in groups of $persist_bunch
$this->doctrine->em->persist($property);
$persist_count++;
// If the number of properties ready to be flushed is the number set in $flush_count, lets flush these properties
if ($persist_count == $flush_count) {
$this->doctrine->em->flush();
$this->doctrine->em->clear();
$this->doctrine->mssql->clear();
}
}
// Flush any remaining properties
$this->doctrine->em->flush();
$i += $flush_count;
}
}
Obviously this is wrong, but I haven't been able to find anywhere to show me a proper example. At the moment it just runs out of memory for some reason and complains about duplicates in the pivot table. How do I get a proper relationship set up so I don't reference the pivot table and can instead directly add FeatureOptions to a Property?
Ok, managed to get it working by changing in Property this:
/**
* #ORM\ManyToMany(targetEntity="FeaturesOption", mappedBy="properties")
*/
protected $featuresOptions;
to this:
/**
* #ORM\ManyToMany(targetEntity="FeaturesOption")
* #ORM\JoinTable(name="properties_features",
* joinColumns={#ORM\JoinColumn(name="property_id", referencedColumnName="legacy_id")},
* inverseJoinColumns={#ORM\JoinColumn(name="feature_id", referencedColumnName="id")}
* )
*/
protected $featuresOptions;
Dropping the pivot table entity, and dropping the inverse reference stuff in the FeaturesOption entity.
I have, two entities, Topic and TopicContent are relation by topic_id.
topic_id in topic table is autoincremet , in topic_content it's not autoincrement.
Because, i need to get topic_id from Topic entity when query it's ok, and then insert data in topic_content table. Help me please, how to do this in symfony with orm. thanks.
TopicContent
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic_content")
*/
class TopicContent
{
/**
*
* #ORM\Column(name="topic_id", type="integer")
* #ORM\Id
*
*/
protected $topic_id;
/**
*
* #ORM\Column(name="topic_text", type="text", nullable=false)
*/
protected $topic_text;
/**
* #ORM\OneToOne(targetEntity="Topic", inversedBy="topicContent", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="topic_id", referencedColumnName="topic_id", onDelete="CASCADE")
*/
private $topic;
/**
* Set topic_id
*
* #param integer $topicId
* #return TopicContent
*/
public function setTopicId($topicId)
{
$this->topic_id = $topicId;
return $this;
}
/**
* Get topic_id
*
* #return integer
*/
public function getTopicId()
{
return $this->topic_id;
}
/**
* Set topic_text
*
* #param string $topicText
* #return TopicContent
*/
public function setTopicText($topicText)
{
$this->topic_text = $topicText;
return $this;
}
/**
* Get topic_text
*
* #return string
*/
public function getTopicText()
{
return $this->topic_text;
}
/**
* Set topic
*
* #param \Socialist\ClubBundle\Entity\Topic $topic
* #return TopicContent
*/
public function setTopic(\Socialist\ClubBundle\Entity\Topic $topic = null)
{
$this->topic = $topic;
return $this;
}
/**
* Get topic
*
* #return \Socialist\ClubBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
}
Topic
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic")
* #ORM\HasLifecycleCallbacks
*/
class Topic
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $topic_id;
/**
* #ORM\Column(type="string", length=200)
*/
protected $topic_title;
/**
* #ORM\Column(type="datetime")
*/
protected $topic_date_add;
/**
* #ORM\Column(type="datetime")
*/
protected $topic_date_edit;
/**
* Get topic_id
*
* #return integer
*/
public function getTopicId()
{
return $this->topic_id;
}
/**
* Set topic_title
*
* #param string $topicTitle
* #return Topic
*/
public function setTopicTitle($topicTitle)
{
$this->topic_title = $topicTitle;
return $this;
}
/**
* Get topic_title
*
* #return string
*/
public function getTopicTitle()
{
return $this->topic_title;
}
/**
* Set topic_date_add
*
* #param \DateTime $topicDateAdd
* #return Topic
*/
public function setTopicDateAdd($topicDateAdd)
{
$this->topic_date_add = $topicDateAdd;
return $this;
}
/**
* Get topic_date_add
*
* #return \DateTime
*/
public function getTopicDateAdd()
{
return $this->topic_date_add;
}
/**
* Set topic_date_edit
*
* #param \DateTime $topicDateEdit
* #return Topic
*/
public function setTopicDateEdit($topicDateEdit)
{
$this->topic_date_edit = $topicDateEdit;
return $this;
}
/**
* Get topic_date_edit
*
* #return \DateTime
*/
public function getTopicDateEdit()
{
return $this->topic_date_edit;
}
/**
* #ORM\PrePersist
*/
public function setTopicDateAddValue() {
if (!$this->getTopicDateAdd())
{
$this->topic_date_add = new \DateTime();
}
}
/**
* #ORM\PreUpdate
*/
public function setTopicDateEditValue()
{
$this->topic_date_edit = new \DateTime();
}
public function __construct()
{
$this->setTopicDateAdd(new \DateTime());
$this->setTopicDateEdit(new \DateTime());
}
/**
* #ORM\OneToOne(targetEntity="TopicContent", mappedBy="topic", cascade={"persist", "remove"})
*/
private $topicContent;
/**
* Set topicContent
*
* #param \Socialist\ClubBundle\Entity\TopicContent $topicContent
* #return Topic
*/
public function setTopicContent(\Socialist\ClubBundle\Entity\TopicContent $topicContent = null)
{
$this->topicContent = $topicContent;
return $this;
}
/**
* Get topicContent
*
* #return \Socialist\ClubBundle\Entity\TopicContent
*/
public function getTopicContent()
{
return $this->topicContent;
}
}
Topic Entity
public function __construct()
{
$this->topicContent = new \Doctrine\Common\Collections\ArrayCollection();
$this->setTopicDateAdd(new \DateTime());
$this->setTopicDateEdit(new \DateTime());
}
/**
* Set topicContent
*
* #param \Socialist\ClubBundle\Entity\TopicContent $topicContent
* #return Topic
*/
public function setTopicContent(\Socialist\ClubBundle\Entity\TopicContent $topicContent = null)
{
$this->topicContent = $topicContent;
return $this;
}
Topic Controller
public function createAction(Request $request)
{
$entity = new Topic();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('topic_show', array('id' => $entity->getTopicId())));
}
return $this->render('SocialistClubBundle:Topic:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
After persisting your Topic Entity, you will get LastInserted topic id from your Topic entity
for example,
$em = $this->getDoctrine()->getManager();
$topic = new \Acme\TestBundle\Entity\Topic();
$topic->setTopicTitle('Your Title');
$em->persist($topic);
$em->flush(); //insert data into table
If insertion is ok $topic entity hold new row object inserted
You can get new topic id by getting
$newTopicId= $topic->getTopicId();
For Topic content Entity,
$topicContent= new new \Acme\TestBundle\Entity\TopicContent();
$topicContent->setTopicId($newTopicId);
$topicContent->setTopicText('Your topic text');
For avoid more confusion Please change your Topic Content Entity as follows,
namespace Socialist\ClubBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="topic_content")
*/
class TopicContent
{
/**
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*
*/
protected $id;
/**
*
* #ORM\Column(name="topic_text", type="text", nullable=false)
*/
protected $topic_text;
/**
* #ORM\OneToOne(targetEntity="Topic", inversedBy="topicContent", cascade={"persist", "remove"})
* #ORM\JoinColumn(name="topic_id", referencedColumnName="topic_id", onDelete="CASCADE")
*/
private $topic;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set topic_text
*
* #param string $topicText
* #return TopicContent
*/
public function setTopicText($topicText)
{
$this->topic_text = $topicText;
return $this;
}
/**
* Get topic_text
*
* #return string
*/
public function getTopicText()
{
return $this->topic_text;
}
/**
* Set topic
*
* #param \Socialist\ClubBundle\Entity\Topic $topic
* #return TopicContent
*/
public function setTopic(\Socialist\ClubBundle\Entity\Topic $topic = null)
{
$this->topic = $topic;
return $this;
}
/**
* Get topic
*
* #return \Socialist\ClubBundle\Entity\Topic
*/
public function getTopic()
{
return $this->topic;
}
}`
The id should be primary key and autoincrement
this will resolve your all 'topic_id' burdens
i'm receiving the following error message upon persisting and flushing an object with its associations:
Catchable Fatal Error: Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
.../vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php on line 519 and defined in
.../vendor/doctrine/common/lib/Doctrine/Common/Collections/ArrayCollection.php line 48
what i have is a single table inheritance with this as the base object:
use Doctrine\ORM\Mapping as ORM;
/**
* ObjectData
*
* #ORM\Table(name="object_data")
* #ORM\Entity(repositoryClass="Edexp\CoreBundle\Entity\ObjectDataRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="entity_name", type="string")
* #ORM\DiscriminatorMap({
* "request" = "Edexp\MessageBundle\Entity\RequestData"
* })
* #ORM\HasLifecycleCallbacks
*/
class ObjectData
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var User
*
* #ORM\OneToMany(targetEntity="User", mappedBy="data")
*/
private $user;
/**
* #var string
*
* #ORM\Column(name="`key`", type="string", length=255)
*/
private $key;
/**
* #var string
*
* #ORM\Column(name="data", type="blob")
*/
private $data;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set created_at
*
* #param \DateTime $createdAt
* #return ObjectData
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
return $this;
}
/**
* Get created_at
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set user
*
* #param User $user
* #return ObjectData
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return User
*/
public function getUser()
{
return $this->user;
}
/**
* Set key
*
* #param string $key
* #return ObjectData
*/
public function setKey($key)
{
$this->key = $key;
return $this;
}
/**
* Get key
*
* #return string
*/
public function getKey()
{
return $this->key;
}
/**
* Set data
*
* #param string $data
* #return ObjectData
*/
public function setData($data)
{
$this->data = $data;
return $this;
}
/**
* Get data
*
* #return string
*/
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prepareForPersist()
{
$this->created_at = new \DateTime();
}
}
and an additional object that inherits from ObjectData:
use Doctrine\ORM\Mapping as ORM;
use MyProject\CoreBundle\Entity\ObjectData;
/**
* RequestData
*
* #ORM\Entity()
*/
class RequestData extends ObjectData
{
/**
* var Request $request
*
* #ORM\ManyToOne(targetEntity="Request", inversedBy="data")
* #ORM\JoinColumn(name="object_id", referencedColumnName="id")
*/
private $request;
/**
* Set request
*
* #param Request $request
* #return RequestData
*/
public function setRequest($request)
{
$this->request = $request;
return $this;
}
/**
* Get request
*
* #return Request
*/
public function getRequest()
{
return $this->request;
}
}
and here's the object that utilizes the RequestData entity:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Request
*
* #ORM\Table(name="requests")
* #ORM\Entity(repositoryClass="RequestRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Request
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Message $message
*
* #ORM\ManyToOne(targetEntity="Message", inversedBy="requests")
*/
private $message;
/**
* #var RequestType $type
*
* #ORM\ManyToOne(targetEntity="RequestType")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(
* targetEntity="RequestData",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $data;
/**
* #var datetime $created_at
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $created_at;
/**
* #var text $comment
*
* #ORM\Column(name="comment", type="text")
*/
private $comment;
/**
* #var ArrayCollection $responses
*
* #ORM\OneToMany(
* targetEntity="Response",
* mappedBy="request",
* cascade={"persist","remove"}
* )
*/
private $responses;
public function __construct()
{
$this->data = new ArrayCollection();
$this->responses = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set message
*
* #param Message $message
*/
public function setMessage($message)
{
$this->message = $message;
}
/**
* Get message
*
* #return Message
*/
public function getMessage()
{
return $this->message;
}
/**
* Set type
*
* #param RequestType $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Get type
*
* #return RequestType
*/
public function getType()
{
return $this->type;
}
/**
* Set created_at
*
* #param datetime $createdAt
*/
public function setCreatedAt($createdAt)
{
$this->created_at = $createdAt;
}
/**
* Get created_at
*
* #return datetime
*/
public function getCreatedAt()
{
return $this->created_at;
}
/**
* Set comment
*
* #param text $comment
*/
public function setComment($comment)
{
$this->comment = $comment;
}
/**
* Get comment
*
* #return text
*/
public function getComment()
{
return $this->comment;
}
/**
* Add response
*
* #param Response $response
*/
public function addResponse($response)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $response->getUser() )
return;
}
$this->responses->add($response);
}
/**
* Get responses
*
* #return ArrayCollection
*/
public function getResponses()
{
return $this->responses;
}
public function hasResponse($user)
{
foreach ( $this->responses as $r ) {
if ( $r->getUser() == $user )
return $r;
}
return null;
}
public function addData($data)
{
$data->setRequest($this);
$this->data->add($data);
}
public function getData()
{
return $this->data;
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$this->created_at = new \DateTime();
}
}
and finally the code that results in an error:
use MyProject\MessageBundle\Entity\Request as MyRequest;
$data = new RequestData();
$data->setUser($user);
$data->setKey('user_id');
$data->setData(6);
$req = new MyRequest();
$req->setMessage($message);
$req->setComment('bla');
$req->setType($doctrine->getRepository('MessageBundle:RequestType')->find(1));
$req->addData($data);
$em->persist($req);
$em->flush();
any suggestions as to what might be wrong here?
cheers
so here's what i had to do in order to make it work.
i had to change the association in ObjectData from:
#ORM\OneToMany(targetEntity="User", mappedBy="data")
to
#ORM\ManyToOne(targetEntity="User", inversedBy="data")
added the data field to the User entity accordingly.
/**
* #var ArrayCollection $data
*
* #ORM\OneToMany(targetEntity="ObjectData", mappedBy="user")
*/
private $data;
and voila, it worked.
Try:
$req->addData(array($data));
Explanation:
arrayCollection constructor type hints an array as its parameter, so you need to always pass it an array.