I create a database and I had the entity file, I added a new column to my table, now how can I update the Entity class and add getter ad setter to this new element ?
the table contains ; userid, username, firstname, password
I added a column "admin" (boolean)
here is my class : Users:
<?php
namespace Login\LoginBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Redirect
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Login\LoginBundle\Entity\Users")
*/
class Users
{
/**
* #var string
*/
private $userName;
/**
* #var string
*/
private $firstName;
/**
* #var string
*/
private $password;
/**
* #var integer
*/
private $userid;
/**
* 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 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 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;
}
/**
* Get userid
*
* #return integer
*/
public function getUserid()
{
return $this->userid;
}
}
The generator bundle gives you a command to generate an entity from a set of fields via the app/console doctrine:generate:entity command.
Internally, this works by using template files to create your new entities, based on your inputs. Unfortunately, the tool does not yet have the ability to modify existing classes.
If you'd like, you can request that feature here: https://github.com/sensiolabs/SensioGeneratorBundle
But in the meantime, your best bet is one of the following:
If you haven't modified anything, you could erase the file and re-create it using app/console doctrine:generate:entity.
You can just add the field yourself, along with the getters, setters, and Doctrine configuration, using the formats you see used for the other fields in that class (this is probably the easier way, to be honest).
Related
when i use mutil database with doctrine to related objects ,it can't find the table in the right way.
ta is table name ,in the acc database.
tb is table name too,in the trade database.
ta record:
id name
1 ta名称
tb record:
id name
1 tb名称
$em=$this->getDoctrine()->getRepository(ta::class,'customer');
$ta=$em->find(2);//now ,it can fetch the data,and the data is right
$tb=$ta->getTbTable();
$szName=$tb->getName(); //i want to get the tb record,it will throw an exception :
...................................
'acc.tb' doesn't exist"
actully,tb is in the trade database.
how to fix these problem
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\PrePersist;
use Doctrine\ORM\Mapping\PreUpdate;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Table(name="ta")
* #ORM\Entity(repositoryClass = "AppBundle\Entity\taRepository")
* #ORM\HasLifecycleCallbacks()
* #package AppBundle\Entity
*/
class ta {
/**
* #ORM\Column(type="integer",unique=true)
* #Assert\NotBlank(message="账号ID不能为空")
* #ORM\Id
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\EntityTrade\tb")
* #ORM\JoinColumn(name="id",referencedColumnName="id")
*/
private $tb_table;
/**
* Set id.
*
* #param int $id
*
* #return ta
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name.
*
* #param string $name
*
* #return ta
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name.
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set tbTable.
*
* #param \AppBundle\EntityTrade\tb|null $tbTable
*
* #return ta
*/
public function setTbTable(\AppBundle\EntityTrade\tb $tbTable = null)
{
$this->tb_table = $tbTable;
return $this;
}
/**
* Get tbTable.
*
* #return \AppBundle\EntityTrade\tb|null
*/
public function getTbTable()
{
return $this->tb_table;
}
}
<?php
namespace AppBundle\EntityTrade;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\PrePersist;
use Doctrine\ORM\Mapping\PreUpdate;
use Doctrine\ORM\Mapping\HasLifecycleCallbacks;
use Symfony\Component\Validator\Constraints as Assert;
/**
* #ORM\Table(name="tb")
* #ORM\Entity(repositoryClass = "AppBundle\EntityTrade\tbRepository")
* #ORM\HasLifecycleCallbacks()
* #package AppBundle\EntityTrade
*/
class tb {
/**
* #ORM\Column(type="integer",unique=true)
* #Assert\NotBlank(message="账号ID不能为空")
* #ORM\Id
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* Set id.
*
* #param int $id
*
* #return tb
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id.
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name.
*
* #param string $name
*
* #return tb
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name.
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
class defaultController{
public function indexAction(){
$em=$this->getDoctrine()->getRepository(ta::class,'customer');
$ta=$em->find(2);
$tb=$ta->getTbTable();
$szName=$tb->getName();
}
}
It will not work in this way. Doctrine's EntityManager only support management of entities within single database, so your cross-database relation between ta and tb will not be established. Please refer this issue in Doctrine bug tracker for more information.
However your goal can be accomplished into slightly different way. You can't establish cross-database relations between entities, but you can, of course, store ids that refers entities into different databases. Hence you can move all cross-database relations logic into repositories. For example let's assume that you have 2 EntityManager for each database: $accEm for acc database and $tradeEm for trade database. Taking in mind that you're using Symfony - they can be configured into DoctrineBundle configuration and then injected into services.
You will need to create some changes into your code:
ta.php, I've omitted most of code to express changes that needs to be made.
namespace AppBundle\Entity;
class ta
{
/**
* #ORM\Column(type="integer", nullable=true)
* #var int
*/
private $tb_table; // Notice that it is not a reference anymore, but simple integer
/**
* Set tbTable.
*
* #param \AppBundle\EntityTrade\tb|null $tbTable
*
* #return ta
*/
public function setTbTable(\AppBundle\EntityTrade\tb $tbTable = null)
{
// You can also consider updating this method to accept plain integers aswel
$this->tb_table = $tbTable instanceof \AppBundle\EntityTrade\tb ? $tbTable->getId() : null;
return $this;
}
/**
* Get tbTable.
*
* #return int|null
*/
public function getTbTable()
{
// Also notice that plain integer is returned, you may want to rename column and method names to reflect this change of column meaning
return $this->tb_table;
}
}
taRepository.php, I've also omitted most of code that can be there
namespace AppBundle\Entity;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
class taRepository extends EntityRepository {
/**
* #var EntityManager
*/
private $tradeEm;
/**
* #param EntityManager $tradeEm
*/
public function setTradeEntityManader(EntityManager $tradeEm)
{
// It is required to pass instance of EntityManager for "trade" database here. It should be done via Symfony services configuration, please refer Symfony documentation on this topic if needed
$this->tradeEm = $tradeEm;
}
/**
* #param ta $ta
* #return \AppBundle\EntityTrade\tb|null
*/
public function getTbTable(ta $ta) {
// This method should be used instead of $ta::getTbTable()
$tbId = $ta->getTbTable();
if ($tbId === null) {
return null;
}
return $this->tradeEm->find(\AppBundle\EntityTrade\tb::class, $tbId);
}
}
defaultController.php
namespace AppBundle\Controller;
use Doctrine\ORM\EntityManager;
class defaultController
{
/**
* #var EntityManager
*/
private $tradeEm;
/**
* #param EntityManager $tradeEm
*/
public function __construct(EntityManager $tradeEm)
{
// Same as before, this should be instance of EntityManager for "trade" database
$this->tradeEm = $tradeEm;
}
public function indexAction()
{
$em = $this->getDoctrine()->getRepository(ta::class, 'customer');
$ta = $em->find(2);
// Notice that we're not receiving "trade" database entity directly, but using corresponding EntityManager instead
$tb = $this->tradeEm->getTbTable($ta);
if ($tb !== null) {
$szName = $tb->getName();
}
}
}
I have a entity :
/**
* #ORM\Entity
* #ORM\Table(name="organization")
*/
class Organization
{
/*
*#ORM\OneToMany(targetEntity="Link" , mappedBy="organization")
*/
private $links;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* #param string $title
* #return Organization
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set site
*
* #param string $site
* #return Organization
*/
public function setSite($site)
{
$this->site = $site;
return $this;
}
/**
* Get site
*
* #return string
*/
public function getSite()
{
return $this->site;
}
public function __construct()
{
$this->links = new ArrayCollection();
}
}
when run command :
php console doctrine:generate:entities News/VillageNewsBundle/Entity/Organization
when i run this command all the getter and setter
will generated but getter and setter for relation not add to my entity?!
That's because your OneToMany annotation is wrong.
You must use the correct doc synthax, which is:
/**
* [...]
*/
Here, it misses one '*' before your OneToMany annotation. Add it and it will work. :-)
Im learning doctrine2. Problem is: I have just updated my entity class. Old version of entity consisted of $id, $name and $username fields. After this update below, I run command doctrine:generate:entities Acme, doctrine:update:schema and etc., but result is still old table with only 3 fields. It looks like old meta-data is saved somewhere. Can someone provide me with information what Im doing wrong ? And why I get old database table instead of new one ? And even how to solve my problem ?
namespace Acme\DemoBundle\Entity;
use Symfony\Component\Security\Core\Role\Role;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\EquatableInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="user")
* #ORM\Entity
*/
class User implements UserInterface, EquatableInterface
{
/**
* #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 string
*
* #ORM\Column(name="roles", type="string", length=50)
*/
private $roles;
/**
* #var array
*
* #ORM\Column(name="apikey", type="array")
*/
private $apiKey;
/**
* #var string
*
* #ORM\Column(name="salt", type="string", length=10)
*/
private $salt;
function __construct($apiKey, $id, $password ,$roles , $salt, $username)
{
$this->apiKey = $apiKey;
$this->id = $id;
$this->password = $password;
$this->roles = $roles;
$this->salt = $salt;
$this->username = $username;
}
/**
* The equality comparison should neither be done by referential equality
* nor by comparing identities (i.e. getId() === getId()).
*
* However, you do not need to compare every attribute, but only those that
* are relevant for assessing whether re-authentication is required.
*
* Also implementation should consider that $user instance may implement
* the extended user interface `AdvancedUserInterface`.
*
* #param UserInterface $user
*
* #return bool
*/
public function isEqualTo(UserInterface $user)
{
if (!$user instanceof User) {
return false;
}
if ($this->password !== $user->getPassword()) {
return false;
}
if ($this->salt !== $user->getSalt()) {
return false;
}
if ($this->username !== $user->getUsername()) {
return false;
}
return true;
}
/**
* 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[] The user roles
*/
public function getRoles()
{
return $this->roles;
}
/**
* Returns the password used to authenticate the user.
*
* This should be the encoded password. On authentication, a plain-text
* password will be salted, encoded, and then compared to this value.
*
* #return string The password
*/
public function getPassword()
{
return $this->password;
}
/**
* 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 $this->salt;
}
/**
* Returns the username used to authenticate the user.
*
* #return string The username
*/
public function getUsername()
{
return $this->username;
}
/**
* #return string
*/
public function getApiKey()
{
return $this->apiKey;
}
/**
* #param string $apiKey
*/
public function setApiKey($apiKey)
{
$this->apiKey = $apiKey;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* #param int $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* 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.
}
}
If the old metadata is saved You have to clear cache
doctrine:cache:clear-metadata Clears all metadata cache for an entity manager
doctrine:cache:clear-query Clears all query cache for an entity manager
doctrine:cache:clear-result Clears result cache for an entity manager
I think you did not executed the update command correctly.
You'll need to force the changes:
php app/console doctrine:schema:update --force
Or dump the SQL and execute it manually:
php app/console doctrine:schema:update --dump-sql
I would like to save my users search on my website. Thaht's why i have a Class User and i would like to create Search Class.
I have done that :
class Search
{
public function __construct()
{
$this->searched_date = new \Datetime();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
private $id;
/**
* #ORM\Id
* #ORM\ManyToOne(targetEntity="test\UserBundle\Entity\User")
*/
private $user;
/**
* #ORM\Column(name="termsearch", type="string", length=255, nullable="true")
*/
private $termsearch;
/**
* #ORM\Column(name="goodtitle", type="string", length=255, nullable="true")
*/
private $goodtitle;
/**
* #ORM\Column(name="searched_date", type="datetime")
*/
private $searched_date;
/**
* Set termsearch
*
* #param text $termsearch
*/
public function setTermsearch($termsearch)
{
$this->termsearch = $termsearch;
}
/**
* Get termsearch
*
* #return text
*/
public function getTermsearch()
{
return $this->termsearch;
}
/**
* Set searched_date
*
* #param datetime $searchedDate
*/
public function setSearchedDate($searchedDate)
{
$this->searched_date = $searchedDate;
}
/**
* Get searched_date
*
* #return datetime
*/
public function getSearchedDate()
{
return $this->searched_date;
}
/**
* Set user
*
* #param test\UserBundle\Entity\User $user
*/
public function setUser(\test\UserBundle\Entity\User $user)
{
$this->user = $user;
}
/**
* Get user
*
* #return test\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Set goodtitle
*
* #param text $goodtitle
*/
public function setGoodtitle($goodtitle)
{
$this->goodtitle = $goodtitle;
}
/**
* Get goodtitle
*
* #return text
*/
public function getGoodtitle()
{
return $this->goodtitle;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
And i would like to insert like that :
$em = $this->getDoctrine()->getEntityManager();
$user = $em->getRepository('TestUserBundle:User')->find($currentuser->getID());
$search = new Search();
$search->setUser($user);
$search->setTermsearch($termsearch);
$search->setGoodtitle($goodtitle);
$em->persist($search);
$em->flush();
Unfortunately i have this error :
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens (500 Internal Server Error)
And in the stack we can found that :
INSERT INTO s_search (user_id, termsearch, goodtitle, searched_date) VALUES (?, ?, ?, ?) ({"1":"c2c","2":"C2C Down The Road","3":{"date":"2012-10-31 00:18:47","timezone_type":3,"timezone":"Europe\/Paris"}})
I don't know how i can create this class Search...
Thank for for you help !
Remove #ORM\Id from the $user as #ManyToOne mapping reference does not require a type. See Doctrine's Annotation Reference for details. Doctrine takes care of the correct column type to hold the reference to another entity.
Make also sure that your User query really returns a valid $user. If it's possible that Search does not have $user, use #JoinColumn annotation to claim the column nullable. See another SO question Doctrine 2 can't use nullable=false in manyToOne relation?
I have a problem while json_encodeing a Entity.
public function jsonvoteAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('KorumAGBundle:AGVote')->findOneById($id);
$response = new Response(json_encode($entity, 200));
$response->headers->set('Content-Type',' application/json');
return $response;
}
This code returns me a the users entity
{"users":{"__isInitialized__":false,"id":null,"nickname":null,"pwd":null,"email":null,"firstname":null,"lastname":null,"poste":null,"addr1":null,"addr2":null,"pc":null,"country":null,"phone":null,"province":null,"acess":null,"site":null,"crew":null,"utilisateur":null}}
And when I var dymp my $entity, it returns both my AGVote and USers entity.
Here is my AGVote Entity
<?php
namespace Korum\AGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Korum\AGBundle\Entity\AGVote
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class AGVote
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* #ORM\Column(type="text")
*/
private $question;
/**
* #ORM\Column(type="smallint")
*/
private $actif;
/**
* #ORM\ManyToOne(targetEntity="\Korum\KBundle\Entity\Users", cascade={"all"})
*/
public $users;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set question
* Nb : Only AG admin can set a question
* #param text $question
*/
public function setQuestion($question)
{
$this->question = $question;
}
/**
* Get question
*
* #return text
*/
public function getquestion()
{
return $this->question;
}
/**
* Set actif
*
* #param smallint $actif
*/
public function setActif($actif)
{
$this->actif = $actif;
}
/**
* Get actif
*
* #return smallint
*/
public function getActif()
{
return $this->actif;
}
/**
* Set Users
*
* #param Korum\KBundle\Entity\Province $Users
*/
public function setUsers(\Korum\KBundle\Entity\Users $users)
{
$this->users = $users;
}
/**
* Get Users
*
* #return Korum\KBundle\Entity\Users
*/
public function getUsers()
{
return $this->users;
}
}
Does anyone have an idea of what happened ?
I tried to install the JSMSerializerBundle but event with Metadata library at version 1.1.
When I want to clear my cache, it failed with error :
See :
JMSSerializerBundle Installation : Catchable Fatal Error: Argument 1 passed to JMSSerializerBundle\Twig\SerializerExtension::__construct()
By default, json_encode only uses public properties.
So it serialized the only public property of AGVote: $users. The content of $users was an instance of User; which public fields were serialized.
You could work around these by adding a toArray() method to your entities, and then doing json_encode($entity->toArray()), but i highly recommend you to have a look and use the JMSSerializedBundle.