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.
Related
I can't access to user entity by topic entity.
In the template twig i use dump to display the result query...:
{% for forum in listForums %}
{{ dump (forum.topics.last)}}
....
we can see that User entity is empty (null):
Topic {#1456 ▼
-Forum: Forum {#435 ▶}
-Posts: PersistentCollection {#1457 ▶}
-id: 65
-title: "How to go over there"
-User: User {#1294 ▼
-_entityPersister: BasicEntityPersister {#1291 ▶}
-_identifier: array:1 [▶]
+__isInitialized__: false
-Topics: null
#id: null
-pseudo: null
-name: null
-firstname: null
-website: null
-avatar: null
-signature: null
-location: null
-registration: null
-lastVisit: null
-rank: null
-nbPost: null
-nbTopic: null
#username: null
#usernameCanonical: null
#email: null
#emailCanonical: null
#enabled: null
#salt: null
#password: null
#plainPassword: null
#lastLogin: null
#confirmationToken: null
#passwordRequestedAt: null
#groups: null
#locked: null
#expired: null
#expiresAt: null
#roles: null
#credentialsExpired: null
#credentialsExpireAt: null
}
-viewCount: 23
-dateCreation: DateTime {#1455 ▶}
-replyCount: 123
-slug: "slug_sluggg"
-genre: "genre"
-lastPost: 25
-content: """
<p>test</p>\r\n
\r\n
<p>test2</p>\r\n
\r\n
<p>test3</p>
"""
}
Part of Controller
class FController extends Controller
{
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$listForums = $em->getRepository('BISSAPForumBundle:Forum')->findAllOrderByCategory();
return $this->render('BISSAPForumBundle:F:index-forum.html.twig', array('listForums' => $listForums, 'user' => $user));
}
}
Topic.php
<?php
namespace BISSAP\ForumBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/*use BISSAP\BodyConcept\Entity\Forum;
*/
/**
* Topic
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\ForumBundle\Entity\TopicRepository")
*/
class Topic
{
/**
* #ORM\ManyToOne(targetEntity="Forum", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(name="forum_id", referencedColumnName="id")
*/
private $Forum;
/**
* #var ArrayCollection $Posts
*
* #ORM\OneToMany(targetEntity="Post", mappedBy="Topic", cascade={"persist", "remove", "merge"})
*/
private $Posts;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #ORM\ManyToOne(targetEntity="BISSAP\UserBundle\Entity\User", inversedBy="Topics", cascade={"persist"})
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $User;
/**
* #var integer
*
* #ORM\Column(name="view_count", type="integer")
*/
private $viewCount;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime")
*/
private $dateCreation;
/**
* #var integer
*
* #ORM\Column(name="reply_count", type="integer")
*/
private $replyCount;
/**
* #var string
*
* #ORM\Column(name="slug", type="string", length=255)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="genre", type="string", length=255)
*/
private $genre;
/**
* #var integer
*
* #ORM\Column(name="last_post", type="integer")
*/
private $lastPost;
/**
* #var string
*
* #ORM\Column(name="content", type="text")
*/
private $content;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Topic
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set user
*
* #param integer $user
* #return Topic
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return integer
*/
public function getUser()
{
return $this->user;
}
/**
* Set viewCount
*
* #param integer $viewCount
* #return Topic
*/
public function setViewCount($viewCount)
{
$this->viewCount = $viewCount;
return $this;
}
/**
* Get viewCount
*
* #return integer
*/
public function getViewCount()
{
return $this->viewCount;
}
/**
* Set dateCreation
*
* #param \DateTime $dateCreation
* #return Topic
*/
public function setDateCreation($dateCreation)
{
$this->dateCreation = $dateCreation;
return $this;
}
/**
* Get dateCreation
*
* #return \DateTime
*/
public function getDateCreation()
{
return $this->dateCreation;
}
/**
* Set replyCount
*
* #param integer $replyCount
* #return Topic
*/
public function setReplyCount($replyCount)
{
$this->replyCount = $replyCount;
return $this;
}
/**
* Get replyCount
*
* #return integer
*/
public function getReplyCount()
{
return $this->replyCount;
}
/**
* Set slug
*
* #param string $slug
* #return Topic
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* Set genre
*
* #param string $genre
* #return Topic
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* #return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* Set lastPost
*
* #param integer $lastPost
* #return Topic
*/
public function setLastPost($lastPost)
{
$this->lastPost = $lastPost;
return $this;
}
/**
* Get lastPost
*
* #return integer
*/
public function getLastPost()
{
return $this->lastPost;
}
/**
* Set content
*
* #param string $content
* #return Topic
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* #return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set forum
*
* #param Forum $forum
* #return Topic
*/
/*public function setForum(\BISSAP\BodyConceptBundle\Entity\Forum $forum)*/
public function setForum(Forum $forum)
{
$this->forum = $forum;
return $this;
}
/**
* Get forum
*
* #return \BISSAP\BodyConceptBundle\Entity\Forum
*/
public function getForum()
{
return $this->forum;
}
/**
* Constructor
*/
public function __construct()
{
$this->posts = new \Doctrine\Common\Collections\ArrayCollection();
$this->dateCreation = new \DateTime();
}
/**
* Add posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
* #return Topic
*/
public function addPost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts[] = $posts;
return $this;
}
/**
* Remove posts
*
* #param \BISSAP\ForumBundle\Entity\Post $posts
*/
public function removePost(\BISSAP\ForumBundle\Entity\Post $posts)
{
$this->posts->removeElement($posts);
}
/**
* Get posts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPosts()
{
return $this->posts;
}
}
User.php
<?php
namespace BISSAP\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* BISSAP\UserBundle\Entity\User
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="BISSAP\UserBundle\Entity\UserRepository")
*/
class User extends BaseUser
{
/**
* #var ArrayCollection $Topics
*
* #ORM\OneToMany(targetEntity="\BISSAP\ForumBundle\Entity\Topic", mappedBy="User", cascade={"persist", "remove", "merge"})
*/
private $Topics;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="pseudo", type="string", length=30, nullable=true)
*/
private $pseudo;
/**
* #ORM\Column(name="name", type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your name.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )
*/
private $name;
/**
* #ORM\Column(name="firstname", type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your firstname.", groups={"Registration", "Profile"})
* #Assert\Length(
* min=3,
* max=255,
* minMessage="The name is too short.",
* maxMessage="The name is too long.",
* groups={"Registration", "Profile"}
* )
*/
private $firstname;
/**
* #var string
*
* #ORM\Column(name="website", type="string", length=100, nullable=true)
*/
private $website;
/**
* #var string
*
* #ORM\Column(name="avatar", type="string", length=100, nullable=true)
*/
private $avatar;
/**
* #var string
*
* #ORM\Column(name="signature", type="string", length=200, nullable=true)
*/
private $signature;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=100, nullable=true)
*/
private $location;
/**
* #var \DateTime
*
* #ORM\Column(name="registration", type="datetime")
*/
private $registration;
/**
* #var \DateTime
*
* #ORM\Column(name="last_visit", type="datetime")
*/
private $lastVisit;
/**
* #var integer
*
* #ORM\Column(name="rank", type="integer", nullable=true)
*/
private $rank;
/**
* #var integer
*
* #ORM\Column(name="nb_post", type="integer", nullable=true)
*/
private $nbPost;
/**
* #var integer
*
* #ORM\Column(name="nb_topic", type="integer", nullable=true)
*/
private $nbTopic;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set pseudo
*
* #param string $pseudo
* #return User
*/
public function setPseudo($pseudo)
{
$this->pseudo = $pseudo;
return $this;
}
/**
* Get pseudo
*
* #return string
*/
public function getPseudo()
{
return $this->pseudo;
}
/**
* 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 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 website
*
* #param string $website
* #return User
*/
public function setWebsite($website)
{
$this->website = $website;
return $this;
}
/**
* Get website
*
* #return string
*/
public function getWebsite()
{
return $this->website;
}
/**
* Set avatar
*
* #param string $avatar
* #return User
*/
public function setAvatar($avatar)
{
$this->avatar = $avatar;
return $this;
}
/**
* Get avatar
*
* #return string
*/
public function getAvatar()
{
return $this->avatar;
}
/**
* Set signature
*
* #param string $signature
* #return User
*/
public function setSignature($signature)
{
$this->signature = $signature;
return $this;
}
/**
* Get signature
*
* #return string
*/
public function getSignature()
{
return $this->signature;
}
/**
* Set location
*
* #param string $location
* #return User
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set registration
*
* #param \DateTime $registration
* #return User
*/
public function setRegistration($registration)
{
$this->registration = $registration;
return $this;
}
/**
* Get registration
*
* #return \DateTime
*/
public function getRegistration()
{
return $this->registration;
}
/**
* Set lastVisit
*
* #param \DateTime $lastVisit
* #return User
*/
public function setLastVisit($lastVisit)
{
$this->lastVisit = $lastVisit;
return $this;
}
/**
* Get lastVisit
*
* #return \DateTime
*/
public function getLastVisit()
{
return $this->lastVisit;
}
/**
* Set rank
*
* #param integer $rank
* #return User
*/
public function setRank($rank)
{
$this->rank = $rank;
return $this;
}
/**
* Get rank
*
* #return integer
*/
public function getRank()
{
return $this->rank;
}
/**
* Set nbPost
*
* #param integer $nbPost
* #return User
*/
public function setNbPost($nbPost)
{
$this->nbPost = $nbPost;
return $this;
}
/**
* Get nbPost
*
* #return integer
*/
public function getNbPost()
{
return $this->nbPost;
}
/**
* Set nbTopic
*
* #param integer $nbTopic
* #return User
*/
public function setNbTopic($nbTopic)
{
$this->nbTopic = $nbTopic;
return $this;
}
/**
* Get nbTopic
*
* #return integer
*/
public function getNbTopic()
{
return $this->nbTopic;
}
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->Topics = new \Doctrine\Common\Collections\ArrayCollection();
$this->registration = new \DateTime();
$this->lastVisit = new \DateTime();
}
/**
* Add Topics
*
* #param \BISSAP\ForumBundle\Entity\Topic $topics
* #return User
*/
public function addTopic(\BISSAP\ForumBundle\Entity\Topic $topics)
{
$this->Topics[] = $topics;
return $this;
}
/**
* Remove Topics
*
* #param \BISSAP\ForumBundle\Entity\Topic $topics
*/
public function removeTopic(\BISSAP\ForumBundle\Entity\Topic $topics)
{
$this->Topics->removeElement($topics);
}
/**
* Get Topics
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getTopics()
{
return $this->Topics;
}
/**
* 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 firstname
*
* #param string $firstname
* #return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* #return string
*/
public function getFirstname()
{
return $this->firstname;
}
}
I would like to see the request generated by Doctrine but i don't know the way to display it.
So i'm trying to access to pseudo user with {{ forum.topics.last.user.pseudo }}
I get Error:
An exception has been thrown during the rendering of a template ("Notice: Undefined property: BISSAP\ForumBundle\Entity\Topic::$user") in BISSAPForumBundle:F:index-forum.html.twig at line 53.
I moved $User by $user and i get :
Impossible to access an attribute ("user") on a boolean variable ("") in BISSAPForumBundle:F:index-forum.html.twig at line 53
UserRepository::findAllOrderByCategory() doesn't exist but
ForumRepository::findAllOrderByCategory() :
class ForumRepository extends EntityRepository
{
public function findAllOrderByCategory()
{
return $this->createQueryBuilder('p')
->leftJoin('p.Category','c')
->orderBy('c.ordre', 'desc')
->getQuery()
->getResult();
}
}
Doctrine is lazy-loading related objects by default, unless the related object is already loaded. Accessing the related object (i.e. echo-ing Topic.user.pseudo) should trigger loading the full object.
See the footnote at: http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#joins
If that doesn't work, could you add a screenshot of the error message and the contents of your UserRepository::findAllOrderByCategory() method in a response?
I have created two bundle using two different vendor names. Two bundle names is-
SystemUsersBundle
Namespace= SystemUsersBundle\Namespace
AppBundle
Namespace= AppBundle\Namespace
Now, I have created two Entity inside two bundle. Entity name given below-
Comment.php – this entity created under AppBundle and it’s namespace
is AppBundle\Entity.
Users.php – this entity created under SystemUsersBundle and it’s
namespace is SystemUsersBundle\Entity.
My directory Structure is-
Now, I wanted to make a relationship between Users.php and Comment.php entity. For this purpose I make a relation between them according to the rule of Doctrine ManyToOne relationship.
Users.php and Comment.php file given below-
Users.php
<?php
namespace SystemUsersBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Users
*
* #ORM\Table("users")
*/
class Users implements AdvancedUserInterface
{
/**
* #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=255)
*/
private $username;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255)
*/
private $email;
/**
* #Gedmo\Slug(fields={"name"}, updatable=false)
* #ORM\Column(length=255, unique=true)
*/
private $slug;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*/
private $plainpassword;
/**
* #var string
*/
private $resetPassword;
/**
* #var array
*
* #ORM\Column(name="roles", type="array")
*/
private $roles = array();
/**
* #var boolean
*
* #ORM\Column(name="app_status", type="boolean")
*/
private $appStatus;
/**
* #var boolean
*
* #ORM\Column(name="is_active",type="boolean")
*/
private $isActive;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
public function __construct()
{
$this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
/**
* 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 name
*
* #param string $name
* #return Users
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* 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 slug
*
* #param string $slug
* #return Users
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
/**
* 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 plainpassword for the application
*
* #param type $plainpassword
*/
function setPlainpassword($plainpassword)
{
$this->plainpassword = $plainpassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getPlainpassword()
{
return $this->plainpassword;
}
/**
* Set resetPassword for the application
*
* #param type $resetPassword
*/
function setResetPassword($resetPassword)
{
$this->resetPassword = $resetPassword;
}
/**
* Get plainpassword for the application
*
* #return type
*/
function getResetPassword()
{
return $this->resetPassword;
}
/**
* Set roles
*
* #param string $roles
* #return Users
*/
public function setRoles($roles)
{
$this->roles = $roles;
return $this;
}
/**
* Get roles
*
* #return string
*/
public function getRoles()
{
$roles = $this->roles;
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
/**
* set salt property of user
*
* #return type
*/
function getSalt()
{
return $this->salt;
}
/**
* Get salt value of user
*
* #param type $salt
*/
function setSalt($salt)
{
$this->salt = $salt;
}
/**
* Set appStatus
*
* #param boolean $appStatus
* #return Users
*/
public function setAppStatus($appStatus)
{
$this->appStatus = $appStatus;
return $this;
}
/**
* Get appStatus
*
* #return boolean
*/
public function getAppStatus()
{
return $this->appStatus;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return Users
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return Users
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get Is active property
*
* #return type
*/
function getIsActive()
{
return $this->isActive;
}
/**
* Set Is active property
*
* #param \SystemUsersBundle\Entity\type $isActive
* #return $users
*/
function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* erase plain password credentials
*/
public function eraseCredentials()
{
$this->setPlainpassword(null);
}
/**
* Checks whether the user's account has expired.
*
* Internally, if this method returns false, the authentication system
* will throw an AccountExpiredException and prevent login.
*
* #return bool true if the user's account is non expired, false otherwise
*
* #see AccountExpiredException
*/
public function isAccountNonExpired()
{
return true;
}
/**
* Checks whether the user is locked.
*
* Internally, if this method returns false, the authentication system
* will throw a LockedException and prevent login.
*
* #return bool true if the user is not locked, false otherwise
*
* #see LockedException
*/
public function isAccountNonLocked()
{
return true;
}
/**
* Checks whether the user's credentials (password) has expired.
*
* Internally, if this method returns false, the authentication system
* will throw a CredentialsExpiredException and prevent login.
*
* #return bool true if the user's credentials are non expired, false otherwise
*
* #see CredentialsExpiredException
*/
public function isCredentialsNonExpired()
{
return true;
}
/**
* Checks whether the user is enabled.
*
* Internally, if this method returns false, the authentication system
* will throw a DisabledException and prevent login.
*
* #return bool true if the user is enabled, false otherwise
*
* #see DisabledException
*/
public function isEnabled()
{
return $this->getIsActive();
}
Comment.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SystemUsersBundle\Entity\Users;
/**
* Comment
*
* #ORM\Table("comment")
* #ORM\Entity
*/
class Comment
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* #var integer
*
* #ORM\Column(name="user_id", type="integer")
*/
private $userId;
/**
* #var boolean
*
* #ORM\Column(name="status", type="boolean")
*/
private $status;
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Comment
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set userId
*
* #param integer $userId
* #return Comment
*/
public function setUserId($userId)
{
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* #return integer
*/
public function getUserId()
{
return $this->userId;
}
/**
* Set status
*
* #param boolean $status
* #return Comment
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Get status
*
* #return boolean
*/
public function getStatus()
{
return $this->status;
}
}
In comment.php file, make relationship using
/**
*
* #ORM\ManyToOne(targetEntity="Users")
*/
protected $owner;
it's give the following error-
But if I wanted make relationship with two entity under same Bundle(like SystemUsersBundle or AppBundle) it works perfectly ok. If you need more information let me know.
The provided syntax #ORM\ManyToOne(targetEntity="Users") means that given entity is at the same namespace as of the current file. Which is not the case. Your mapping should be like this:
#ORM\ManyToOne(targetEntity="SystemUsersBundle\Entity\Users")
When entities are in different namespace, you should always provide the full path.
If you need to set a relation between your two entities just make it all in one bundle, why you use two bundle if they depends on each other.
take a look at this :
A bundle is meant to be something that can be reused as a stand-alone piece of software. If UserBundle cannot be used "as is" in other Symfony apps, then it shouldn't be its own bundle. Moreover, if InvoiceBundle depends on ProductBundle, then there's no advantage to having two separate bundles.
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.
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();