I have register form.
When I save the user, i want to add row in other database table. The second table is for role and it has only 2 fields: user_id and role_id.
This is my structure of database:
CREATE TABLE `roles` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQ_B63E2EC75E237E06` (`name`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=3
;
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`userName` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
`password` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
`fullName` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
`email` VARCHAR(255) NOT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQ_1483A5E9586CA949` (`userName`),
UNIQUE INDEX `UNIQ_1483A5E9E7927C74` (`email`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
AUTO_INCREMENT=5
;
CREATE TABLE `user_roles` (
`user_id` INT(11) NOT NULL,
`role_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `IDX_54FCD59FA76ED395` (`user_id`),
INDEX `IDX_54FCD59FD60322AC` (`role_id`),
CONSTRAINT `FK_54FCD59FA76ED395` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
CONSTRAINT `FK_54FCD59FD60322AC` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;
So, here is my UserController, where I am saving the user:
namespace AppBundle\Controller;
use AppBundle\Entity\User;
use AppBundle\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserController extends Controller
{
/**
* #Route("/register", name="user_register")
* #param Request $request
* #param UserPasswordEncoderInterface $passwordEncoder
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function registerAction(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$password = $passwordEncoder->encodePassword($user,$user->getPlainPassword());
$user->setPassword($password);
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute("cat_index");
}
return $this->render('users/register.html.twig',
array('form' => $form->createView()));
}
}
I want every user to have role with id=1. So every registered user will have ROLE_USER.
In my Entity User i have not a setter for role. i have only getter. How to add and setter which is checking for role with id 1 and set the role for the user?
Here is my User Entity:
<?php
namespace AppBundle\Entity;
use AppBundle\AppBundle;
use AppBundle\Controller\SecurityController;
use AppBundle\Repository\RoleRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use AppBundle\Entity\Role;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use AppBundle\Repository;
/**
* User
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="userName", type="string", length=255, unique=true)
*/
private $userName;
/**
* #var string
*/
private $plainPassword;
/**
* #var string
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var string
*
* #ORM\Column(name="fullName", type="string", length=255)
*/
private $fullName;
/**
* #var string
*
* #ORM\Column(name="email", type="string", length=255, unique=true)
*/
private $email;
/**
* #ORM\ManyToMany(targetEntity="AppBundle\Entity\Role")
* #ORM\JoinTable(name="user_roles",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")})
* #var Collection|Role[]
*/
private $roles;
/**
* User constructor.
*/
public function __construct()
{
$this->roles = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* 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 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 fullName
*
* #param string $fullName
*
* #return User
*/
public function setFullName($fullName)
{
$this->fullName = $fullName;
return $this;
}
/**
* Get fullName
*
* #return string
*/
public function getFullName()
{
return $this->fullName;
}
/**
* 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;
}
/**
* #return array
*/
public function getRoles()
{
$roles = [];
foreach ($this->roles as $role){
$roles[] = $role->getName();
}
if(empty($roles)){
$roles[] = 'ROLE_USER';
}
return $roles;
}
/**
* 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()
{
// TODO: Implement getSalt() method.
}
/**
* 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()
{
// TODO: Implement eraseCredentials() method.
}
public function serialize()
{
return serialize([
$this->getId(),
$this->getUserName(),
$this->getPassword()
]);
}
public function unserialize($serialized)
{
list(
$this->id,
$this->userName,
$this->password
) = unserialize($serialized);
}
/**
* #return string
*/
public function getPlainPassword(): string
{
return $this->plainPassword.'';
}
/**
* #param string $plainPassword
*/
public function setPlainPassword(string $plainPassword)
{
$this->plainPassword = $plainPassword;
}
}
I am using symfony 3
How to do it? Thanks!
On your UserType you can set your roles field to use EntityType documentation. That will automatically save the roles entity on flush.
Related
I am new to Symfony2 and Doctrine, i am stuck a little bit. Error receiving while saving to the database.
An exception occurred while executing 'INSERT INTO tho_provider (provid_name, provid_logo, provid_logo_path, created_time, provider_created_by) VALUES (?, ?, ?, ?, ?)' with params ["test", {}, "qwwwww", "2015-08-11 16:03:15", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'provider_created_by' cannot be null
I have the form where i am only getting provider name input and logo, rest is i am handling in the controller, Including provider_created_by which gets null just after the flush, before the flush command its showing the value.
public function createAction(Request $request)
{
$user = $this->getUser();
$entity = new Provider();
$entity->setProvidLogoPath("qwwwww");
$entity->setProviderCreatedBy($user);
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
//$entity->setCreatedBy($user);
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('provider_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
I have entities, PROVIDER and USER.
User's can create many provider and providers only belongs to one user. One to many relationship.
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Provider
*
* #ORM\Table(name="tho_provider")
* #ORM\Entity(repositoryClass="AppBundle\Entity\ProviderRepository")
* #Vich\Uploadable
* #ORM\HasLifecycleCallbacks()
*/
class Provider
{
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="providers")
* #ORM\JoinColumn(name="provider_created_by", referencedColumnName="id")
*/
protected $users;
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #ORM\Column(name="provid_name", type="string", length=255)
*/
private $providName;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="general_image", fileNameProperty="provid_logo")
*
* #var File
*/
private $imageFile;
/**
* #var string
*
* #ORM\Column(name="provid_logo", type="string", length=255)
*/
private $providLogo;
/**
* #var string
*
* #ORM\Column(name="provid_logo_path", type="string", length=255)
*/
private $providLogoPath;
/**
* #var \DateTime
* #Assert\Type("\DateTime")
* #ORM\Column(name="created_time", type="datetime")
*/
private $createdTime;
/**
* #var integer
*
* #ORM\Column(name="provider_created_by", type="integer")
*/
public $providerCreatedBy;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set providName
*
* #param string $providName
* #return Provider
*/
public function setProvidName($providName)
{
$this->providName = $providName;
return $this;
}
/**
* Get providName
*
* #return string
*/
public function getProvidName()
{
return $this->providName;
}
/**
* Set providLogo
*
* #param string $providLogo
* #return Provider
*/
public function setProvidLogo($providLogo)
{
$this->providLogo = $providLogo;
return $this;
}
/**
* Get providLogo
*
* #return string
*/
public function getProvidLogo()
{
return $this->providLogo;
}
/**
* Set providLogoPath
*
* #param string $providLogoPath
* #return Provider
*/
public function setProvidLogoPath($providLogoPath)
{
$this->providLogoPath = $providLogoPath;
return $this;
}
/**
* Get providLogoPath
*
* #return string
*/
public function getProvidLogoPath()
{
return $this->providLogoPath;
}
/**
* Set createdTime
*
* #param \DateTime $createdTime
* #return Provider
*/
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
return $this;
}
/**
* Get createdTime
*
* #return \DateTime
*/
public function getCreatedTime()
{
return $this->createdTime;
}
/**
* Set users
*
* #param \AppBundle\Entity\User $users
* #return Provider
*/
public function setUsers(\AppBundle\Entity\User $users = null)
{
$this->users = $users;
return $this;
}
/**
* Get users
*
* #return \AppBundle\Entity\User
*/
public function getUsers()
{
return $this->users;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTime('now');
}
}
/**
* #return File
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #ORM\PrePersist
*/
public function setCreatedTimeValue()
{
$this->createdTime = new \DateTime();
}
/**
* Set providerCreatedBy
*
* #param integer $providerCreatedBy
* #return Provider
*/
public function setProviderCreatedBy($providerCreatedBy)
{
$this->providerCreatedBy = $providerCreatedBy;
return $this;
}
/**
* Get providerCreatedBy
*
* #return integer
*/
public function getProviderCreatedBy()
{
return $this->providerCreatedBy;
}
}
USER:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* User
*
* #ORM\Table(name="tho_user")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
* #UniqueEntity(fields="email",message = "This email already exist.")
* #UniqueEntity(fields = "username",message = "This username already taken")
*/
class User implements AdvancedUserInterface, \Serializable
{
/**
* #ORM\OneToMany(targetEntity="Provider", mappedBy="user")
*/
protected $providers;
public function __construct()
{
$this->providers = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*#Assert\NotBlank(message="Username is required!")
* #Assert\Length(min=3,minMessage="Minimum 3 characters long.")
* #ORM\Column(name="username", type="string", length=255)
*/
protected $username;
/**
* #var string
*
*
* #ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* #var array
*
* #ORM\Column(name="roles",type="json_array")
*/
private $roles = array();
/**
* #var bool
*
* #ORM\Column(name="is_active",type="boolean")
*/
private $isActive = true;
/**
* #var string
*#Assert\NotBlank()
* #Assert\Email
* #ORM\Column(name="email",type="string", length=255)
*/
private $email;
/**
* #var string
*#Assert\NotBlank()
*
* #ORM\Column(name="first_name",type="string", length=255)
*/
private $firstName;
/**
* #var string
*#Assert\NotBlank()
* #ORM\Column(name="last_name",type="string", length=255)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="iata",type="string", length=255)
*/
private $iata;
/**
* #var string
*
* #ORM\Column(name="job_title",type="string", length=255)
*/
private $jobTitle;
/**
* #var string
*
* #ORM\Column(name="agency_phone",type="string", length=255)
*/
private $agencyPhone;
/**
* #var string
*
* #ORM\Column(name="emergency_mobile",type="string", length=255)
*/
private $emergencyMobile;
/**
* Storing password temporarily
* #Assert\NotBlank()
* #Assert\Length(min=6,minMessage="Minimum 6 characters long.")
* #var string
*/
private $plainPassword;
/**
* Get id
*
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* 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 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;
}
public function getRoles()
{
$roles = $this->roles;
$roles[] = 'ROLE_ADMIN';
return array_unique($roles);
}
public function setRoles(array $roles)
{
$this->roles = $roles;
return $this;
}
public function eraseCredentials()
{
$this->setPlainPassword(null);
}
public function getSalt()
{
return null;
}
/**
* #return boolean
*/
public function isIsActive()
{
return $this->isActive;
}
/**
* #param boolean $isActive
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
/**
* 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 true;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
/**
* 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;
}
/**
* (PHP 5 >= 5.1.0)<br/>
* String representation of object
* #link http://php.net/manual/en/serializable.serialize.php
* #return string the string representation of the object or null
*/
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password
));
}
/**
* (PHP 5 >= 5.1.0)<br/>
* Constructs the object
* #link http://php.net/manual/en/serializable.unserialize.php
* #param string $serialized <p>
* The string representation of the object.
* </p>
* #return void
*/
public function unserialize($serialized)
{
list(
$this->id,
$this->username,
$this->password
) = unserialize($serialized);
}
/**
* #return string
*/
public function getFirstName()
{
return $this->firstName;
}
/**
* #param string $firstName
*/
public function setFirstName($firstName)
{
$this->firstName = $firstName;
}
/**
* #return string
*/
public function getLastName()
{
return $this->lastName;
}
/**
* #param string $lastName
*/
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* #return string
*/
public function getIata()
{
return $this->iata;
}
/**
* #param string $iata
*/
public function setIata($iata)
{
$this->iata = $iata;
}
/**
* #return string
*/
public function getJobTitle()
{
return $this->jobTitle;
}
/**
* #param string $jobTitle
*/
public function setJobTitle($jobTitle)
{
$this->jobTitle = $jobTitle;
}
/**
* #return string
*/
public function getAgencyPhone()
{
return $this->agencyPhone;
}
/**
* #param string $agencyPhone
*/
public function setAgencyPhone($agencyPhone)
{
$this->agencyPhone = $agencyPhone;
}
/**
* #return string
*/
public function getEmergencyMobile()
{
return $this->emergencyMobile;
}
/**
* #param string $emergencyMobile
*/
public function setEmergencyMobile($emergencyMobile)
{
$this->emergencyMobile = $emergencyMobile;
}
/**
* #return string
*/
public function getPlainPassword()
{
return $this->plainPassword;
}
/**
* #param string $plainPassword
*/
public function setPlainPassword($plainPassword)
{
$this->plainPassword = $plainPassword;
}
/**
* Set provider
*
* #param \AppBundle\Entity\Provider $provider
* #return User
*/
public function setProvider(\AppBundle\Entity\Provider $provider = null)
{
$this->provider = $provider;
return $this;
}
/**
* Get provider
*
* #return \AppBundle\Entity\Provider
*/
public function getProvider()
{
return $this->provider;
}
/**
* Add providers
*
* #param \AppBundle\Entity\Provider $providers
* #return User
*/
public function addProvider(\AppBundle\Entity\Provider $providers)
{
$this->providers[] = $providers;
return $this;
}
/**
* Remove providers
*
* #param \AppBundle\Entity\Provider $providers
*/
public function removeProvider(\AppBundle\Entity\Provider $providers)
{
$this->providers->removeElement($providers);
}
/**
* Get providers
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProviders()
{
return $this->providers;
}
}
Your metadata is
/**
* #var integer
*
* #ORM\Column(name="provider_created_by", type="integer")
*/
public $providerCreatedBy;
but you are passing an object (probably null):
$user = $this->getUser();
/* ... */
$entity->setProviderCreatedBy($user);
And the setter has no type hint:
public function setProviderCreatedBy($providerCreatedBy)
{
$this->providerCreatedBy = $providerCreatedBy;
return $this;
}
You must change your mapping of $providerCreatedBy to ManyToOne with User entity.
Check if your user has been logged in, $this->getUser() returns null if user is anonymous, also I think you should change your mapping info for providerCreatedBy field, from column type integer to ManyToOne relationship with User class..
I've created an Entity to store some data i'm pulling via an api
When i try to findByOne to see if the entry already exists, i get an error saying the field is not recognised.
I've done a php app/console doctrine:schema:update --force
I can see the table in my mySQL manager with the right fieldname 'StadiumID'
So why cant doctrine find it when i do findByOne();
My Entity Class:
<?php
namespace FantasyPro\DataBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stadium
*
* #ORM\Table("fp_stadium")
* #ORM\Entity(repositoryClass="FantasyPro\DataBundle\Entity\StadiumRepository")
*/
class Stadium
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="StadiumID", type="integer", length=2, nullable=false, unique=true)
*/
private $stadiumID;
/**
* #var string
*
* #ORM\Column(name="Name", type="string", length=100, nullable=false)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="City", type="string", length=50, nullable=false)
*/
private $city;
/**
* #var string
*
* #ORM\Column(name="State", type="string", length=10, nullable=true)
*/
private $state;
/**
* #var string
*
* #ORM\Column(name="Country", type="string", length=2, nullable=false)
*/
private $country;
/**
* #var integer
*
* #ORM\Column(name="Capacity", type="integer", length=32, nullable=true)
*/
private $capacity;
/**
* #var string
*
* #ORM\Column(name="PlayingSurface", type="string", length=50, nullable=true)
*/
private $playingSurface;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set stadiumID
*
* #param integer $stadiumID
* #return Stadium
*/
public function setStadiumID($stadiumID)
{
$this->stadiumID = $stadiumID;
return $this;
}
/**
* Get stadiumID
*
* #return integer
*/
public function getStadiumID()
{
return $this->stadiumID;
}
/**
* Set name
*
* #param string $name
* #return Stadium
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set city
*
* #param string $city
* #return Stadium
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* #return string
*/
public function getCity()
{
return $this->city;
}
/**
* Set state
*
* #param string $state
* #return Stadium
*/
public function setState($state)
{
$this->state = $state;
return $this;
}
/**
* Get state
*
* #return string
*/
public function getState()
{
return $this->state;
}
/**
* Set country
*
* #param string $country
* #return Stadium
*/
public function setCountry($country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* #return string
*/
public function getCountry()
{
return $this->country;
}
/**
* Set capacity
*
* #param integer $capacity
* #return Stadium
*/
public function setCapacity($capacity)
{
$this->capacity = $capacity;
return $this;
}
/**
* Get capacity
*
* #return integer
*/
public function getCapacity()
{
return $this->capacity;
}
/**
* Set playingSurface
*
* #param string $playingSurface
* #return Stadium
*/
public function setPlayingSurface($playingSurface)
{
$this->playingSurface = $playingSurface;
return $this;
}
/**
* Get playingSurface
*
* #return string
*/
public function getPlayingSurface()
{
return $this->playingSurface;
}
}
The code i'm using to add the data if it does not exist and to update it if it does exist:
<?php
namespace FantasyPro\DataBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FantasyPro\DataBundle\Entity\Stadium;
class DefaultController extends Controller
{
public function indexAction($name)
{
return $this->render('DataBundle:Default:index.html.twig', array('name' => $name));
}
public function updateStadiumAction(){
//get list of stadiums
$client = $this->container->get('fantasyapi');
$stadiumData = $client->Stadiums();
//var_dump($stadiumData);
//get the entity manager
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('DataBundle:Stadium');
$log = $stadiumData;
foreach($stadiumData as $stadium){
// Get the current stadium in the list
$criteria = array("StadiumID" =>$stadium['StadiumID']);
var_dump($criteria);
$storedStadium = $repo->FindOneBy($criteria);
if (!$storedStadium) {
/* throw $this->createNotFoundException(
'No product found for id '.$stadium['StadiumID']
);*/
//no stadium exists with the StadiumID passed
//create a new entry
$entry = new Stadium();
$entry->setStadiumID($stadium['StadiumID']);
$entry->setName($stadium['Name']);
$entry->setCity($stadium['City']);
$entry->setState($stadium['State']);
$entry->setCountry($stadium['Country']);
$entry->setCapacity($stadium['Capacity']);
$entry->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($entry);
$log .= 'Added New Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}else{
$storedStadium->setStadiumID($stadium['StadiumID']);
$storedStadium->setName($stadium['Name']);
$storedStadium->setCity($stadium['City']);
$storedStadium->setState($stadium['State']);
$storedStadium->setCountry($stadium['Country']);
$storedStadium->setCapacity($stadium['Capacity']);
$storedStadium->setPlayingSurface($stadium['PlayingSurface']);
$em->persist($storedStadium);
$log .= 'Updated Stadium: '.$stadium['StadiumID'].' : '.$stadium['Name'].'<br>';
}
}
//$em->flush();
return $this->render('DataBundle:Default:index.html.twig', array('log' => $log));
}
}
The property name is actually:
private $stadiumID;
So you should do :
$repo->findOneBy(array('stadiumID' => $value));
so change this row:
$criteria = array("StadiumID" =>$stadium['StadiumID']);
to this:
$criteria = array("stadiumID" =>$stadium['StadiumID']);
Doctrine's main role is to connect your application layer(entites) to the database layer(tables). So doctrine tries to translate request comming from the application layer to the database. Even if you named your field in the database "StadiumID"or "table_name_snake_case", when you call findOneBy(array($property => $value)), doctrine expects $property to refer to the property name, and it will translate this to SQL to something like 'SELECT FROM .... where StadiumID = :value'
For others who still have the problem,
make sur that you have puted the sign '=>' instead of ',' when calling the function findOneBy(...)
So instead of :
findOneBy(["code" , "Code-Example"]);
do that :
findOneBy(["code" => "Code-Example"]);
Also, make sure the doctrine naming strategy is specified:
doctrine:
orm:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
this is the doctrine's default naming strategy. This way doctrine knows how to map Entity property names to column names.
Note that, naming strategy configuration might be in different levels of doctrine configuration. For example, in another repo it is configured like this:
doctrine:
orm:
default_entity_manager: shopping
entity_managers:
shopping:
naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware
This is my controller - right from documentation
<?php
namespace Votes\VotesBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Votes\VotesBundle\Entity\File as File;
class FileController extends Controller
{
/**
* #Template()
*/
public function newAction()
{
$file = new File();
$form = $this->createFormBuilder($file)
->add('name')
->add('file','file')
->getForm()
;
if ($this->getRequest()->getMethod() === 'POST') {
$form->bind($this->getRequest());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($file);
$uploadableManager = $this->get('stof_doctrine_extensions.uploadable.manager');
// Here, "getMyFile" returns the "UploadedFile" instance that the form bound in your $myFile property
$uploadableManager->markEntityToUpload($file, $file->getFile());
$em->flush();
$this->redirect($this->generateUrl('/file/new'));
}
}
return array('form' => $form->createView());
}
}
Here's my File entity
<?php
se Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* File
*
* #ORM\Table(name="files")
* #ORM\Entity
* #Gedmo\Uploadable( allowOverwrite=true, appendNumber=true, filenameGenerator="SHA1")
*/
class File
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="path", type="string")
* #Gedmo\UploadableFilePath
*/
private $path;
/**
* #ORM\Column(name="name", type="string")
* #Gedmo\UploadableFileName
*/
private $name;
/**
* #ORM\Column(name="mime_type", type="string")
* #Gedmo\UploadableFileMimeType
*/
private $mimeType;
/**
* #ORM\Column(name="size", type="decimal")
* #Gedmo\UploadableFileSize
*/
private $size;
private $file;
public function setFile($file)
{
$this->file = $file;
return $this;
}
public function getFile()
{
return $this->file;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* #param string $path
* #return File
*/
public function setPath($path)
{
$this->path = $path;
return $this;
}
/**
* Get path
*
* #return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set name
*
* #param string $name
* #return File
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set mimeType
*
* #param string $mimeType
* #return File
*/
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
return $this;
}
/**
* Get mimeType
*
* #return string
*/
public function getMimeType()
{
return $this->mimeType;
}
/**
* Set size
*
* #param string $size
* #return File
*/
public function setSize($size)
{
$this->size = $size;
return $this;
}
/**
* Get size
*
* #return string
*/
public function getSize()
{
return $this->size;
}
}
I get this error when submit form:
An exception occurred while executing 'INSERT INTO files (path, name, mime_type, size) VALUES (?, ?, ?, ?)' with params [null, "asdasdasd", null, null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'path' cannot be null
If I'm correct - the uploadable extension - must fill my File entity with
correct data in events? I'm right?
I make the assumption when an entity has a OneToMany relationship with another, the children entities will be populated when querying the parent entity.
$account = $this->Repository()->findById($organization, $id, $accountList);
print_r($account->getAttributes()); //I would expect the children to be populated/returned when making this call
I would expect that the AccountAttributes would be returned for the Account but $account->getAttributes() returns null.
Any Ideas?
Account Entity
<?php
namespace Application\AccountBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Application\AccountBundle\Entity\AccountAttribute;
/**
* Account
*
* #ORM\Table(name="accounts")
* #ORM\Entity(repositoryClass="Application\AccountBundle\Repository\AccountRepository")
*/
class Account
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="display_name", type="string", length=255)
*/
private $displayName;
/**
* #var \Application\OrganizationBundle\Entity\Organization
*
* #ORM\ManyToOne(targetEntity="Application\OrganizationBundle\Entity\Organization")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
* })
*/
private $organization;
/**
* #var boolean
*
* #ORM\Column(name="active", type="boolean")
*/
private $active;
/**
* #var \DateTime
*
* #ORM\Column(name="deactivated", type="datetime")
*/
private $deactivated;
/**
* #var boolean
*
* #ORM\Column(name="deleted", type="boolean")
*/
private $deleted;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
/**
*
* #var ArrayCollection
*
* #ORM\OneToMany(targetEntity="AccountAttribute", mappedBy="account", cascade={"ALL"}, indexBy="attribute")
*
*/
private $attributes;
public function __construct()
{
$this->attributes = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set displayName
*
* #param string $displayName
* #return Account
*/
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
return $this;
}
/**
* Get displayName
*
* #return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Set active
*
* #param boolean $active
* #return Account
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
* Get active
*
* #return boolean
*/
public function getActive()
{
return $this->active;
}
/**
* Set deactivated
*
* #param \DateTime $deactivated
* #return Account
*/
public function setDeactivated($deactivated)
{
$this->deactivated = $deactivated;
return $this;
}
/**
* Get deactivated
*
* #return \DateTime
*/
public function getDeactivated()
{
return $this->deactivated;
}
/**
* Set deleted
*
* #param boolean $deleted
* #return Account
*/
public function setDeleted($deleted)
{
$this->deleted = $deleted;
return $this;
}
/**
* Get deleted
*
* #return boolean
*/
public function getDeleted()
{
return $this->deleted;
}
/**
* Set updated
*
* #param \DateTime $updated
* #return Account
*/
public function setUpdated($updated)
{
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* #return \DateTime
*/
public function getUpdated()
{
return $this->updated;
}
/**
* Set created
*
* #param \DateTime $created
* #return Account
*/
public function setCreated($created)
{
$this->created = $created;
return $this;
}
/**
* Get created
*
* #return \DateTime
*/
public function getCreated()
{
return $this->created;
}
public function getOrganization()
{
return $this->organization;
}
public function getAttributes()
{
return $this->attributes;
}
public function setAttributes($attributes)
{
foreach($attributes as $item)
{
$this->addAttribute($item);
}
return $this;
}
public function addAttribute(AccountAttribute $attribute)
{
$this->attributes->add($attribute);
return $this;
}
public function getAttributeCollection()
{
$data = array();
$attributes = $this->getAttributes();
foreach ($attributes as $item)
{
$data[$item->getDataKey()] = $item->getDataValue();
}
return $data;
}
}
Account Attribute Entity
<?php
namespace Application\AccountBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Application\AccountBundle\Entity\Account;
use Application\AccountBundle\Entity\AccountAttribute;
use Application\OrganizationBundle\Entity\Organization;
/**
* Account
*
* #ORM\Table(name="accountattribute")
* #ORM\Entity(repositoryClass="Application\AccountBundle\Repository\AccountAttributeRepository")
*/
class AccountAttribute
{
/**
* #var \Application\AccountBundle\Entity\Account
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Account", inversedBy="attributes")
* #ORM\JoinColumn(name="account_id", referencedColumnName="id")
*/
private $account;
/**
* #var \Application\OrganizationBundle\Entity\Organization
* #ORM\Id
* #ORM\ManyToOne(targetEntity="Application\OrganizationBundle\Entity\Organization")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="organization_id", referencedColumnName="id")
* })
*/
private $organization;
/**
* #var string
* #ORM\Id
* #ORM\Column(type="string")
*/
private $dataKey;
/**
* #var text
* #ORM\Column(type="text")
*/
private $dataValue;
/**
* #var \DateTime
* #ORM\Column(name="updated", type="datetime")
*/
private $updated;
/**
* #var \DateTime
*
* #ORM\Column(name="created", type="datetime")
*/
private $created;
public function __construct(Account $account, $organizationId, $key, $value )
{
$this->account = $account;
$this->organizationId = $organizationId;
$this->dataKey = $key;
$this->dataValue = $key;
}
public function getKey()
{
return $this->dataKey;
}
public function setKey($key)
{
$this->dataKey = $key;
return $this;
}
public function getValue()
{
return $this->dataValue;
}
public function setValue($value)
{
$this->dataValue = $value;
return $this;
}
public function getAccount()
{
return $this->account;
}
public function setAccount(Account $account)
{
$this->account = $account;
return $this;
}
}
Account Repository
<?php
namespace Application\AccountBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;
use Doctrine\ORM\Query;
use Application\AccountBundle\Entity\Account;
/**
* AccountRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class AccountRepository extends EntityRepository
{
public function findById($organization_id, $id, $accountList)
{
if( empty( $accountList ) )
return null;
$em = $this->getEntityManager();
$emConfig = $em->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
$q = $em
->createQuery(
"SELECT a
FROM ApplicationAccountBundle:Account a
WHERE
a.id IN ( " . implode(',', $accountList ) . ") AND
a.deleted = false AND
a.organization = :organization_id AND
a.id = :id AND
(
a.active = 1 OR
(
a.active = 0 AND
MONTH(a.deactivated) >= :current_month AND
YEAR(a.deactivated) >= :current_year
)
)
"
)
->setParameters(
array(
'id' => $id,
'organization_id' => $organization_id,
'current_month' => date( "n" ),
'current_year' => date( "Y" )
)
);
try {
$account = $q->getOneOrNullResult();
} catch (NoResultException $e) {
}
return $account;
}
public function findAllAccounts($organization_id, $accountList)
{
if( empty( $accountList ) )
return null;
$em = $this->getEntityManager();
$emConfig = $em->getConfiguration();
$emConfig->addCustomDatetimeFunction('YEAR', 'DoctrineExtensions\Query\Mysql\Year');
$emConfig->addCustomDatetimeFunction('MONTH', 'DoctrineExtensions\Query\Mysql\Month');
$emConfig->addCustomDatetimeFunction('DAY', 'DoctrineExtensions\Query\Mysql\Day');
$q = $em
->createQuery(
"SELECT e
FROM ApplicationAccountBundle:Account a
WHERE
a.id IN ( " . implode(',', $accountList ) . ") AND
a.deleted = false AND
a.organization = :organization_id AND
(
a.active = 1 OR
(
a.active = 0 AND
MONTH(a.deactivated) >= :current_month AND
YEAR(a.deactivated) >= :current_year
)
)
"
)
->setParameters(
array(
'organization_id' => $organization_id,
'current_month' => date( "n" ),
'current_year' => date( "Y" )
)
);
try {
$accounts = $q->getResult();
} catch (NoResultException $e) {
}
return $accounts;
}
public function findByACL($userIdentity, $mask, $className)
{
$sql = <<<SELECTCLAUSE
SELECT oid.object_identifier
FROM acl_entries ent
JOIN acl_object_identities oid ON
oid.class_id = ent.class_id
JOIN acl_security_identities s ON
s.id = ent.security_identity_id
JOIN acl_classes cls ON
cls.id = ent.class_id
WHERE
ent.object_identity_id IS NOT NULL AND
(ent.mask & %d) AND
s.identifier = %s AND
cls.class_type = %s
GROUP BY
oid.object_identifier;
SELECTCLAUSE;
$connection = $this->getEntityManager()->getConnection();
$query = sprintf(
$sql,
$mask,
$connection->quote("{$userIdentity->getClass()}-{$userIdentity->getUsername()}"),
$connection->quote($className)
);
//Execute query to get all of the IDs
$ids = $connection->executeQuery($query)->fetchAll(\PDO::FETCH_COLUMN);
return $ids;
}
public function save(Account $account)
{
$em = $this->getEntityManager();
$em->getConnection()->beginTransaction();
$em->persist($account);
try {
$em->flush();
$em->getConnection()->commit();
} catch (\Exception $e) {
$em->getConnection()->rollback();
echo "Unable to save Account";
}
return $account;
}
}
Table Structures
CREATE TABLE `accounts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`organization_id` int(11) NOT NULL,
`display_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1',
`deactivated` datetime DEFAULT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`updated` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`created` datetime NOT NULL,
PRIMARY KEY (`id`),
KEY `IDX_FA6F25A332C8A3DE` (`organization_id`),
CONSTRAINT `FK_FA6F25A332C8A3DE` FOREIGN KEY (`organization_id`) REFERENCES `organizations` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `accountattribute` (
`account_id` int(11) NOT NULL,
`organization_id` int(11) NOT NULL,
`dataKey` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`dataValue` text COLLATE utf8_unicode_ci NOT NULL,
`updated` datetime NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`account_id`,`organization_id`,`dataKey`),
KEY `organization_id` (`organization_id`),
CONSTRAINT `accountattribute_ibfk_2` FOREIGN KEY (`organization_id`) REFERENCES `organizations` (`id`),
CONSTRAINT `accountattribute_ibfk_1` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
here is your problem: in your repository call you only selected a, therefore only the account will get populated.
I started practicing with symfony 2. So my question is about this command:
php app/console doctrine:schema:update --dump-sql
This is the result of this command execution:
CREATE TABLE Article (id INT AUTO_INCREMENT NOT NULL, image_id INT NOT NULL, publication TINYINT(1) NOT NULL, date DATETIME NOT NULL, titre VARCHAR(255) NOT NULL, auteur VARCHAR(255) NOT NULL, contenu LONGTEXT NOT NULL, UNIQUE INDEX UNIQ_CD8737FA3DA5256D (image_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE Image (id INT AUTO_INCREMENT NOT NULL, url VARCHAR(255) NOT NULL, alt VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE Voiture (id INT AUTO_INCREMENT NOT NULL, nom VARCHAR(255) NOT NULL, modele VARCHAR(255) NOT NULL, couleur VARCHAR(255) NOT NULL, date_creation DATE NOT NULL, photo LONGTEXT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
ALTER TABLE Article ADD CONSTRAINT FK_CD8737FA3DA5256D FOREIGN KEY (image_id) REFERENCES Image (id)
This command makes me crazy, it generates not only the related tables but also other tables of another entities!!!
I removed all my previous databases but still get the same problem.
I need just the voiture table. All the other tables belongs to an other previous database.
How can I stop that??
this is my entities code:
car entity:
<?php
namespace Younga\RentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Car
*/
class Car
{
/**
* #var integer
*/
private $id;
/**
* #var integer
*/
private $nombre;
/**
* #var string
*/
private $nom;
/**
* #var string
*/
private $modele;
/**
* #var string
*/
private $couleur;
/**
* #var \DateTime
*/
private $datecreation;
/**
* #var string
*/
private $photo;
public function __construct()
{
$this->datecreation = new \Datetime;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param integer $nombre
* #return Car
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return integer
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set nom
*
* #param string $nom
* #return Car
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set modele
*
* #param string $modele
* #return Car
*/
public function setModele($modele)
{
$this->modele = $modele;
return $this;
}
/**
* Get modele
*
* #return string
*/
public function getModele()
{
return $this->modele;
}
/**
* Set couleur
*
* #param string $couleur
* #return Car
*/
public function setCouleur($couleur)
{
$this->couleur = $couleur;
return $this;
}
/**
* Get couleur
*
* #return string
*/
public function getCouleur()
{
return $this->couleur;
}
/**
* Set datecreation
*
* #param \DateTime $datecreation
* #return Car
*/
public function setDatecreation($datecreation)
{
$this->datecreation = $datecreation;
return $this;
}
/**
* Get datecreation
*
* #return \DateTime
*/
public function getDatecreation()
{
return $this->datecreation;
}
/**
* Set photo
*
* #param string $photo
* #return Car
*/
public function setPhoto($photo)
{
$this->photo = $photo;
return $this;
}
/**
* Get photo
*
* #return string
*/
public function getPhoto()
{
return $this->photo;
}
}
commentaire entity:
<?php
namespace Younga\RentBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Commentaire
*/
/**
* #ORM\#ORM\Entity
*
*
*/
class Commentaire
{
/**
* #ORM\ManyToOne(targetEntity="Younga\RentBundle\Entity\Voiture")
* #ORM\JoinColumn(nullable=false)
*
*/
private $voiture;
/**
* #var integer
*/
private $id;
/**
* #var string
*/
private $auteur;
/**
* #var string
*/
private $contenu;
/**
* #var \DateTime
*/
private $datecomment;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set auteur
*
* #param string $auteur
* #return Commentaire
*/
public function setAuteur($auteur)
{
$this->auteur = $auteur;
return $this;
}
/**
* Get auteur
*
* #return string
*/
public function getAuteur()
{
return $this->auteur;
}
/**
* Set contenu
*
* #param string $contenu
* #return Commentaire
*/
public function setContenu($contenu)
{
$this->contenu = $contenu;
return $this;
}
/**
* Get contenu
*
* #return string
*/
public function getContenu()
{
return $this->contenu;
}
/**
* Set datecomment
*
* #param \DateTime $datecomment
* #return Commentaire
*/
public function setDatecomment($datecomment)
{
$this->datecomment = $datecomment;
return $this;
}
/**
* Get datecomment
*
* #return \DateTime
*/
public function getDatecomment()
{
return $this->datecomment;
}
/**
* #ORM\prePersist
*/
public function increase()
{
$nbCommentaires = $this->getVoiture()->getNbCommentaires();
$this->getVoiture()->setNbCommentaires($nbCommentaires+1);
}
/**
* #ORM\preRemove
*/
public function decrease()
{
$nbCommentaires = $this->getVoiture()->getNbCommentaires();
$this->getVoiture()->setNbCommentaires($nbCommentaires-1);
}
}
I need just the related tables to my current entity. It call all the previous entity that I created last time.
Thanks in advance and sorry for my English.
I suppose that you have annotations in your Entities like:
namespace Your\OwnBundle\Entity;
use Whatever\You\Use\Here;
/**
* Myentity
*
* #ORM\Table(name="myentity")
* #ORM\Entity
*/
class Myentity
{
/**
* #var integer
*
* #ORM\Id
* #ORM\Column(name="id", type="smallint", nullable=false)
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
//... more code
{
Try to remove the annotations #ORM\Table(name="myentity") and #ORM\Entity. This way I think that Symfony will not recognize them as Entities to being taken into account.
Hope I helped you, mate!