I had a many-to-many using a User and Account entity. I needed to add an isOwner field to the association table so I changed it to a one-to-many / many-to-one relation. Below are my 3 entities (user, account, useraccount).
When I persist the user, the user record and account record are both added, but the association record is not. I am also unsure as to how I can set the isOwner field whilst persisting the user.
Does anyone know how the association record can be persisted? Should the association record be added automatically?
User:
/**
* xxx\CoreBundle\Entity\User
*
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User implements UserInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $firstName
*
* #ORM\Column(name="firstName", type="string", length=255, nullable=false)
* #Assert\NotBlank()
*/
private $firstName;
/**
* #var Account
*
* #ORM\OneToMany(targetEntity="UserAccount", mappedBy="user", cascade={"persist"})
*/
private $account;
public function __construct()
{
$this->account = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set firstName
*
* #param string $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* Get firstName
*
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* Add account
*
* #param xxx\CoreBundle\Entity\Account $account
*/
public function addAccount(\xxx\CoreBundle\Entity\Account $account)
{
$this->account[] = $account;
}
/**
* Get account
*
* #return Doctrine\Common\Collections\Collection
*/
public function getAccount()
{
return $this->account;
}
}
Account:
/**
* xxx\CoreBundle\Entity\Account
*
* #ORM\Table(name="account")
* #ORM\Entity(repositoryClass="xxx\CoreBundle\Repository\AccountRepository")
*/
class Account
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string $name
*
* #ORM\Column(name="name", type="string", length=255, nullable=false)
* #Assert\NotBlank()
*/
private $name;
/**
* #var User
*
* #ORM\OneToMany(targetEntity="UserAccount", mappedBy="account", cascade={"persist"})
*/
private $user;
public function __construct()
{
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add user
*
* #param xxx\CoreBundle\Entity\User $user
*/
public function addUser(\xxx\CoreBundle\Entity\User $user)
{
$this->user[] = $user;
}
/**
* Get user
*
* #return Doctrine\Common\Collections\Collection
*/
public function getUser()
{
return $this->user;
}
}
UserAccount:
/**
* xxx\CoreBundle\Entity\UserAccount
*
* #ORM\Table(name="user_account")
* #ORM\Entity
*/
class UserAccount
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="account", cascade={"persist"})
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity="Account", inversedBy="user", cascade={"persist"})
*/
private $account;
/**
* #var boolean $isOwner
*
* #ORM\Column(name="isOwner", type="boolean", nullable=false)
*/
private $isOwner;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get isOwner
*
* #return bool
*/
public function getIsOwner()
{
return $this->isOwner;
}
/**
* Set isOwner
*
* #param string $isOwner
*/
public function setIsOwner($isOwner)
{
$this->isOwner = $isOwner;
}
/**
* Set user
*
* #param xxx\CoreBundle\Entity\User $user
*/
public function setUser(\xxx\CoreBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return xxx\CoreBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set account
*
* #param xxx\CoreBundle\Entity\Account $account
*/
public function setAccount(\xxx\CoreBundle\Entity\Account $account)
{
$this->account = $account;
}
/**
* Get account
*
* #return xxx\CoreBundle\Entity\Account
*/
public function getAccount()
{
return $this->account;
}
}
Controller:
$account = new Account();
$account->setName('Test account');
$user = new User();
$user->setFirstName('John');
$user->addAccount($account);
$manager->persist($user);
$manager->flush();
You are trying to persist an account as UserAccount entity. Try this:
$account = new Account();
$account->setName('Test account');
$user = new User();
$user->setFirstName('John');
$user_account = new UserAccount();
$user_account->setAccount($account);
$user_account->setUser($user);
$manager->persist($user);
$manager->flush();
Related
I have a 2 entities with one to one relation. One User = One Cart and One Cart = One User. First, when i try to add product to the current logged in user bag there are no problems, but when i add the second product, it throws the following exception:
An exception occurred while executing 'INSERT INTO cart (name, price, image, user_id) VALUES (?, ?, ?, ?)' with params ["Olympus - TG-4", "379.99", "65d30071a19252f3361af3b2e134b0f4", 8]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '8' for key 'UNIQ_BA388B7A76ED395'
Here is User Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User implements UserInterface
{
const ROLE_USER = 'ROLE_USER';
const ROLE_EDITOR= 'ROLE_EDITOR';
const ROLE_ADMIN= 'ROLE_ADMIN';
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #Assert\Email(
* message = "The email '{{ value }}' is not a valid email."
* )
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* #Assert\Length(
* min = 4,
* max = 10,
* minMessage = "Your username must be at least {{ limit }} characters long.",
* maxMessage = "Your username cannot be longer than {{ limit }} characters."
* )
* #var string
* #ORM\Column(name="username", type="string", length=255, unique=true)
*/
private $username;
/**
* #Assert\Length(
* min = 4,
* max = 20,
* minMessage = "Your name must be at least {{ limit }} characters long.",
* maxMessage = "Your name cannot be longer than {{ limit }} characters."
* )
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #Assert\Length(
* min = 4,
* max = 10,
* minMessage = "Your password must be at least {{ limit }} characters long.",
* maxMessage = "Your password cannot be longer than {{ limit }} characters."
* )
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #Assert\Image(mimeTypes={"image/png", "image/jpeg"}, maxSize="5M")
*/
private $image_form;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\Product", mappedBy="user")
*/
private $products;
/**
* #ORM\Column(name="role", type="string", length=255)
*/
private $role;
/**
* One user has One Cart
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Cart", mappedBy="user")
*/
private $cart;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set name
*
* #param string $name
*
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set image
*
* #param string $image
*
* #return User
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* #return mixed
*/
public function getImageForm()
{
return $this->image_form;
}
/**
* #param mixed $image_form
*/
public function setImageForm($image_form)
{
$this->image_form = $image_form;
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* #return (Role|string)[] The user roles
*/
public function getRoles()
{
return explode(',', $this->getRole());
}
/**
* Returns the salt that was originally used to encode the password.
*
* This can return null if the password was not encoded using a salt.
*
* #return string|null The salt
*/
public function getSalt()
{
return null;
}
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*/
public function eraseCredentials()
{
return null;
}
public function getDefaultRole()
{
return self::ROLE_USER;
}
/**
* #return mixed
*/
public function getRole()
{
return $this->role;
}
/**
* #param mixed $role
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* #param array $roles
*/
public function setRoles($roles){
$this->setRole(implode(',', $roles));
}
/**
* #return mixed
*/
public function getProducts()
{
return $this->products;
}
/**
* #param mixed $products
*/
public function setProducts($products)
{
$this->products = $products;
}
/**
* #return mixed
*/
public function getCart()
{
return $this->cart;
}
/**
* #param mixed $cart
*/
public function setCart($cart)
{
$this->cart = $cart;
}
}
Here is Cart Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Cart
*
* #ORM\Table(name="cart")
* #ORM\Entity(repositoryClass="AppBundle\Repository\CartRepository")
*/
class Cart
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="price", type="string", length=255)
*/
private $price;
/**
* #var string
*
* #ORM\Column(name="image", type="string", length=255, nullable=true)
*/
private $image;
/**
* #Assert\Image(mimeTypes={"image/png", "image/jpeg"}, maxSize="5M")
*/
private $image_form;
/**
* One cart has One User
* #ORM\OneToOne(targetEntity="AppBundle\Entity\User", inversedBy="cart")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Cart
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set price
*
* #param string $price
*
* #return Cart
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
* Get price
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
* Set image
*
* #param string $image
*
* #return Cart
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* #return mixed
*/
public function getImageForm()
{
return $this->image_form;
}
/**
* #param mixed $image_form
*/
public function setImageForm($image_form)
{
$this->image_form = $image_form;
}
/**
* #return mixed
*/
public function getUser()
{
return $this->user;
}
/**
* #param mixed $user
*/
public function setUser($user)
{
$this->user = $user;
}
}
And The Cart Controller:
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Cart;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class CartController extends Controller
{
/**
* #Route("/cart/{id}", name="cart")
* #param $id
* #return \Symfony\Component\HttpFoundation\Response
*/
public function listUserCartAction($id)
{
$cart = $this->getDoctrine()->getRepository('AppBundle:Cart')->findAll($id);
return $this->render('cart/cart.view.html.twig', array(
'cart' => $cart
));
}
/**
* #Route("/cart/add/{id}", name="add_to_cart")
* #return \Symfony\Component\HttpFoundation\Response
* #internal param $id
*/
public function addToCartAction($id)
{
$cart = new Cart();
$product = $this->getDoctrine()->getRepository('AppBundle:Product')->find($id);
$productName = $product->getName();
$productPrice = $product->getPrice();
/** #var UploadedFile $file */
$filename = md5($product->getName());
//Get Current User Id
$user = $this->get('security.token_storage')->getToken()->getUser();
$cart->setName($productName);
$cart->setPrice($productPrice);
$cart->setImage($filename);
$cart->setUser($user);
$em = $this->getDoctrine()->getManager();
$em->persist($cart);
$em->flush();
return $this->render('cart/cart.view.html.twig');
}
}
The problem you have is based in the generation of the Database Schema, as the error says you have a constrain error, on a duplicated key (user_id).
You must change the UNIQUE INDEX, i think you should change it for INDEX(user_id)
It is because you have bidirectional one to one relation. Try removing the following code from User Entity
/**
* One user has One Cart
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Cart", mappedBy="user")
*/
private $cart;
The problem is that for a particular user, you are creating a new cart for every product that is added. Instead, cart should just have id (primary key) and user_id and there should be a new table (cart_products) which has the mapping of product_id to card_id.
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.
Excuse me for my English.
I have 3 classes: User, Category and Service.
When I do even a simple query to the database for Service, for example findAll(), my computer hangs... At the same time, the query for Category and User are good.
Thank you for your help!
User.php
namespace General\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your type.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max="255",
* minMessage="The type is too short.",
* maxMessage="The type is too long.",
* groups={"Registration", "Profile"}
* )
*/
protected $type;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set type
*
* #param string $type
* #return User
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return string
*/
public function getType()
{
return $this->type;
}
}
Category.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Category
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\CategoryRepository")
*/
class Category
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\OneToMany(targetEntity="\General\AnnuaireBundle\Entity\Service", mappedBy="categories")
*/
private $services;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
$this->services = new 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;
}
/**
* Set description
*
* #param string $description
* #return Category
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Category
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* #ORM\PrePersist()
*/
public function setCreatedAt($createdAt = null) {
$this->createdAt = null === $createdAt ? new \DateTime() : $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Add services
*
* #param \General\AnnuaireBundle\Entity\Service $services
* #return Category
*/
public function addService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services[] = $services;
return $this;
}
/**
* Remove services
*
* #param \General\AnnuaireBundle\Entity\Service $services
*/
public function removeService(\General\AnnuaireBundle\Entity\Service $services)
{
$this->services->removeElement($services);
}
/**
* Get services
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getServices()
{
return $this->services;
}
}
Service.php
namespace General\AnnuaireBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Service
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="General\AnnuaireBundle\Entity\ServiceRepository")
*/
class Service
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var boolean
*
* #ORM\Column(name="statut", type="boolean")
*/
private $statut;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #ORM\ManyToOne(targetEntity="\General\AnnuaireBundle\Entity\Category", inversedBy="services")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $categories;
/**
* #ORM\ManyToOne(targetEntity="\General\UserBundle\Entity\User")
*/
private $users;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
* #return Service
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set description
*
* #param string $description
* #return Service
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set statut
*
* #param boolean $statut
* #return Service
*/
public function setStatut($statut)
{
$this->statut = $statut;
return $this;
}
/**
* Get statut
*
* #return boolean
*/
public function getStatut()
{
return $this->statut;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Service
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set categories
*
* #param \General\AnnuaireBundle\Entity\Category $categories
* #return Service
*/
public function setCategories(\General\AnnuaireBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
/**
* Get categories
*
* #return \General\AnnuaireBundle\Entity\Category
*/
public function getCategories()
{
return $this->categories;
}
/**
* Set users
*
* #param \General\UserBundle\Entity\User $users
* #return Service
*/
public function setUsers(\General\UserBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* #return \General\UserBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
}
Controller.php
public function showServicesAction()
{
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services,
)
);
}
If I modified my function as:
$user = $this->container->get('security.context')->getToken()->getUser();
$user_id = $user->getId();
// var_dump($user_id); ALL IS RIGHT
$em = $this->getDoctrine()->getManager();
$services = $em->getRepository('GeneralAnnuaireBundle:Service')->findAll();
// var_dump($user_id); ALL IS RIGHT
// IF: var_dump($services[0]); COMPUTER HUNGS
// IF: echo count($services); RESPONSE RIGHT
// IF:
return $this->render('GeneralAnnuaireBundle:General:list_services.html.twig',
array('services'=>$services, ));
// SCREEN WHITE
If you print object in browser it get hanged because symphony object contains lots of info. suppose if you have relation with other tables it will have current tables info as well as other related tables info (Schema, Data, Relationship etc.) as well so it might 99% chance to hanged the browser. Better to print "echo count($services)" to check object exists or not.
Try Debug::dump($service) or any variable - you will be able to see the objects (without the proxy)
I have a problem with Doctrine2 in Symfony2 and two relationed entities.
I have a class Users
class Users
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="username", type="string", length=50)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=50)
*/
private $password;
/**
* #var boolean
*
* #ORM\Column(name="type", type="boolean")
*/
private $type;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #var string
*
* #ORM\Column(name="first_name", type="string", length=100)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=100)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="tel", type="string", length=255)
*/
private $tel;
/**
* #var string
*
* #ORM\Column(name="url_img", type="string", length=255)
*/
private $urlImg;
/**
* #var string
*
* #ORM\Column(name="company", type="string", length=255)
*/
private $company;
/**
* #ORM\OneToOne(targetEntity="Providers", mappedBy="userId", cascade={"persist"})
*/
protected $provider;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
* #return Users
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* #return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* #param string $password
* #return Users
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set type
*
* #param boolean $type
* #return Users
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type
*
* #return boolean
*/
public function getType()
{
return $this->type;
}
/**
* Set idPrest
*
* #param integer $idPrest
* #return Users
*/
public function setIdPrest($idPrest)
{
$this->idPrest = $idPrest;
return $this;
}
/**
* Get idPrest
*
* #return integer
*/
public function getIdPrest()
{
return $this->idPrest;
}
/**
* Set idEmbaucher
*
* #param integer $idEmbaucher
* #return Users
*/
public function setIdEmbaucher($idEmbaucher)
{
$this->idEmbaucher = $idEmbaucher;
return $this;
}
/**
* Get idEmbaucher
*
* #return integer
*/
public function getIdEmbaucher()
{
return $this->idEmbaucher;
}
/**
* Set email
*
* #param string $email
* #return Users
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set firstName
*
* #param string $firstName
* #return Users
*/
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 Users
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
return $this;
}
/**
* Get lastName
*
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* Set tel
*
* #param string $tel
* #return Users
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* #return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set urlImg
*
* #param string $urlImg
* #return Users
*/
public function setUrlImg($urlImg)
{
$this->urlImg = $urlImg;
return $this;
}
/**
* Get urlImg
*
* #return string
*/
public function getUrlImg()
{
return $this->urlImg;
}
/**
* Set company
*
* #param string $company
* #return Users
*/
public function setCompany($company)
{
$this->company = $company;
return $this;
}
/**
* Get company
*
* #return string
*/
public function getCompany()
{
return $this->company;
}
/**
* Set provider
*
* #param Providers $provider
* #return Users
*/
public function setProvider($provider = null)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return Providers
*/
public function getProvider()
{
return $this->provider;
}
}
in relation with class provider on OneToOne (inheriting)
class Providers
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToOne(targetEntity="Users", inversedBy="provider")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $userId;
/**
* #ORM\OneToOne(targetEntity="Advertisement", mappedBy="provider")
*/
protected $advertisement;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* #param \leBonCoinDesServices\MainBundle\Entity\Users $userId
* #return Providers
*/
public function setUserId($userId = null)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return \leBonCoinDesServices\MainBundle\Entity\Users
*/
public function getUserId()
{
return $this->userId;
}
}
I just want to get the fields user_id created from the relationship for be able to when I create a user get the id of this one and give it to the user_id field.
And when I test my controller to create a user and a provider :
public function newUserAction()
{
$user = new Users();
$user->setUsername("gokusan");
$user->setPassword("test");
$user->setType("p");
$user->setEmail("test#msn.com");
$user->setFirstName("KHALIL");
$user->setLastName("Ahmed");
$user->setTel("0142021148");
$user->setUrlImg("img/test/");
$user->setCompany("Push&Pull");
$this->getDoctrine()->getEntityManager()->persist($user);
$this->getDoctrine()->getEntityManager()->flush();
$provider = new Providers();
$id = $user->getId();
$provider->setUserId($id);
$this->getDoctrine()->getEntityManager()->persist($provider);
$this->getDoctrine()->getEntityManager()->flush();
die("User Added");
}
that puts me error :
Warning: spl_object_hash() expects parameter 1 to be object, integer given in F:\Programs Files\Program Files\wamp\www\leboncoindesservices\vendor\doctrine\orm\lib\Doctrine\ORM\UnitOfWork.php line 1367
Your Providers::setUserId($userId) expects $userId to be of type \leBonCoinDesServices\MainBundle\Entity\Users and not of type integer. So you should be able to pass your Users object to the $provider like
$user = new Users();
...
$provder = new Providers();
...
$provider->setUserId($user);
This is my user entity
<?php
namespace Monse\UsuariosBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\UsuariosBundle\Entity\Usuario
*
* #ORM\Table(name="users")
* #ORM\Entity
*/
class Usuario implements UserInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="Monse\ClientesBundle\Entity\Cliente")
* #ORM\JoinColumn(name="cliente_id", referencedColumnName="id",nullable=true)
*/
protected $cliente;
/**
* #var string $usuario
*
* #ORM\Column(name="usuario", type="string", length=255, unique=true)
*/
protected $usuario;
/**
* #var string $email
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
protected $email;
/**
* #var string $password
*
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #var string $salt
*
* #ORM\Column(name="salt", type="string", length=255)
*/
protected $salt;
/**
* #var date $ultimo_ingreso
*
* #ORM\Column(name="ultimo_ingreso", type="date")
*/
protected $ultimo_ingreso;
/**
* #var date $fecha_alta
*
* #ORM\Column(name="fecha_alta", type="date")
*/
protected $fecha_alta;
/**
* #ORM\ManyToOne(targetEntity="Monse\UsuariosBundle\Entity\Rol")
* #ORM\JoinColumn(name="rol", referencedColumnName="id",nullable=false)
*/
protected $rol;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
public function setCliente(\Monse\ClientesBundle\Entity\Cliente $cliente)
{
$this->cliente = $cliente;
}
/**
* Get cliente
*
* #return integer
*/
public function getCliente()
{
return $this->cliente;
}
/**
* Set usuario
*
* #param string $usuario
*/
public function setUsuario($usuario)
{
$this->usuario = $usuario;
}
/**
* Get usuario
*
* #return string
*/
public function getUsuario()
{
return $this->usuario;
}
/**
* Set email
*
* #param string $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set contrasena
*
* #param string $contrasena
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* Get contrasena
*
* #return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set salt
*
* #param string $salt
*/
public function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Get salt
*
* #return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set ultimo_ingreso
*
* #param date $ultimoIngreso
*/
public function setUltimoIngreso($ultimoIngreso)
{
$this->ultimo_ingreso = $ultimoIngreso;
}
/**
* Get ultimo_ingreso
*
* #return date
*/
public function getUltimoIngreso()
{
return $this->ultimo_ingreso;
}
/**
* Set fecha_alta
*
* #param date $fechaAlta
*/
public function setFechaAlta($fechaAlta)
{
$this->fecha_alta = $fechaAlta;
}
/**
* Get fecha_alta
*
* #return date
*/
public function getFechaAlta()
{
return $this->fecha_alta;
}
/**
* Set rol
*
* #param integer $rol
*/
public function setRol(\Monse\UsuariosBundle\Entity\Rol $rol)
{
$this->rol = $rol;
}
/**
* Get rol
*
* #return integer
*/
public function getRol()
{
return $this->rol;
}
public function __construct()
{
$this->fecha_alta = new \DateTime();
}
function equals(\Symfony\Component\Security\Core\User\UserInterface $usuario)
{
return $this->getUsuario() == $usuario->getUsername();
}
function eraseCredentials()
{
}
function getRoles()
{
}
function getUsername()
{
return $this->getUsuario();
}
}
and this is my roles entity
<?php
namespace Monse\UsuariosBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\UsuariosBundle\Entity\Rol
*
* #ORM\Table(name="roles")
* #ORM\Entity
*/
class Rol implements RoleInterface
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $role
*
* #ORM\Column(name="rol", type="string", length=255)
*/
protected $role;
/**
* #var string $denominacion
*
* #ORM\Column(name="denominacion", type="string", length=255)
*/
protected $denominacion;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set rol
*
* #param string $rol
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* Get rol
*
* #return string
*/
public function getRole()
{
return $this->role;
}
public function setDenominacion($denominacion)
{
$this->denominacion = $denominacion;
}
/**
* Get denominacion
*
* #return string
*/
public function getDenominacion()
{
return $this->denominacion;
}
public function __toString() {
return $this->denominacion;
}
}
Please HELP, i don't know what i'm doing wrong?
I need to administrate ROLES, that's why i have the entity.
In the Rol entity
rol has ROLE_ADMIN, ROLE_USER...
denominacion is Super Admin, Admin, User, etc...
I need to retreive ROL
Function getRoles() in Usuario should return an array of role names. Why yours is empty?
public function getRoles()
{
return $this->roles->map(function($r) { return $r->getRole(); })
->toArray();
}
Usuario has a many to one relation with role. Are you sure this is correct? The above example assumes that you have a collection of roles.