This question already has answers here:
Doctrine2 ORM does not save changes to a DateTime field
(3 answers)
Closed 8 years ago.
I think I have found a bug which I can not find solution ..
I try to update the datetime field, but do not update it, don't gives me an error.
Move all other fields modifies them correctly, but the datetime field no.
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyOwnBundle:Events')->find($id);
$In = $entity->getDateIn();
$In->modify('+1 day');
$entity->setDateIn($In);
$em->flush();
I also tried to insert a DateTime() object directly but does not update at all!
$entity->setDateIn(new \DateTime());
Is there a solution to this problem?
I installed symfony 2.1 and doctrine 2.3.3
EDIT
Event entity:
/**
* Events
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="My\OwnBundle\Entity\EventsRepository")
*/
class Events
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=100)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="description", type="text")
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="dateIn", type="datetime")
*/
private $dateIn;
/**
* #var \DateTime
*
* #ORM\Column(name="dateOut", type="datetime")
*/
private $dateOut;
....
/**
* Set dateIn
*
* #param \DateTime $dateIn
* #return Events
*/
public function setDateIn($dateIn)
{
$this->dateIn = $dateIn;
return $this;
}
/**
* Get dateIn
*
* #return \DateTime
*/
public function getDateIn()
{
return $this->dateIn;
}
/**
* Set dateOut
*
* #param \DateTime $dateOut
* #return Events
*/
public function setDateOut($dateOut)
{
$this->dateOut = $dateOut;
return $this;
}
/**
* Get dateOut
*
* #return \DateTime
*/
public function getDateOut()
{
return $this->dateOut;
}
....
The modify() method will not update the entity since Doctrine tracks DateTime objects by reference. You need to clone your existing DateTime object, giving it a new reference. Modify the new one and then set is as a new timestamp.
For more information, see the article in the Doctrine Documentation.
the entity is right, but you need to persist your entity with $em->persist($entity) and you don't need to set again the date because the datetime is passed by reference
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('MyOwnBundle:Events')->find($id);
$entity->getDateIn()->modify('+1 day');
$em->persist($entity);
$em->flush();
Related
hi i'm doing a survey i could record the progress of the quiz according to the user
example: user is at question 15/50 he must be able to disconnect and continue where he was stopping.
I manage to assign the answers to the user, but not to worry about the progress. thank you so much
so here I got my answer via the post method
my controlleur to save answer for a user..
class DefaultController extends Controller
{
/**
* #Route("/Reponse/thematique", name="thematique_reponse")
* #Method({"GET", "POST"})
*/
public function reponseThematique(Request $request)
{
//instance des repository
$userSlpRepo = $this->getDoctrine()->getRepository(UserSlp::class);
$reponseThematiqueRepo = $this->getDoctrine()->getRepository(Reponse_thematique::class);
$questionMangerRepo = $this->getDoctrine()->getRepository(Manger::class);//here all the questions
$em = $this->getDoctrine()->getManager();
$userSlp = $userSlpRepo->findOneByGaeaUserId($this->getUser()->getId());
$datas = $request->request->all();
foreach ($datas as $data => $value ){
$question = $questionMangerRepo->find($data);
$answer = new Reponse_thematique;
$answer->setManger($question);
$answer->setValue($value);
$answer->setUserSlp($userSlp);
$em->persist($answer);
$em->flush();
}
return new response('ok');
}
I thought to make a relationship with an entity "questionnaire-progress" for example or we will have an id, question_id, user_id and why not a column or we would put a boolean if the questionaire is finished or not.
/**
* SurveyProgress
*
* #ORM\Table(name="survey_progress", indexes={#ORM\Index(name="IDX_7EF6B461B3FE509D",
* columns={"questionnaire_id"}), #ORM\Index(name="IDX_7EF6B4611E27F6BF",
* columns={"manger_id"}), #ORM\Index(name="IDX_7EF6B461FDDFEACC",
* columns={"userSlp_id"})})
* #ORM\Entity
*/
class QuestionnaireProgress
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var bool
*
* #ORM\Column(name="done", type="boolean", nullable=false)
*/
private $done;
/**
* #var \Question
*
* #ORM\ManyToOne(targetEntity="manger")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="question_id", referencedColumnName="id")
* })
*/
private $manger;
/**
* #var \Survey
*
* #ORM\ManyToOne(targetEntity="questionnaire")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="questionnaire_id", referencedColumnName="id")
* })
*/
private $questionnaire;
/**
* #var \UserSlp
*
* #ORM\ManyToOne(targetEntity="UserSlp")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="userSlp_id", referencedColumnName="id")
* })
*/
private $userslp;
}
You could save the answers everytime the user answers. Then, you'll have this information stored.
I suppose a Survey contains a list of Questions. You can then get the total number of questions.
If you save the answers when the user answers, the number of Reponse_thematique for a given UserSlp and a given Survey / the total number of questions will give you the progress
I have an Angular4 app working with Symfony3/Doctrine2 Rest Api.
Both in Angular and Symfony, I have those entities :
Table
TableNode
Node
The relation between Table and Node is :
Table (OneToMany) TableNode (ManyToOne) Node
What is a "ManyToMany" relation with attributes.
In the Angular app, I create a new Table (form a TableModel that has exactly the same properties that the Table entity in the Symfony app).
This Table contains several Node entities that come from the Api (so they already exists in my database).
What I want is to create a new Table that contains new TableNode entities and each TableNode should contain existing Node entities.
When I want to save my table within the db, I call my Api through a Put action :
/**
* PUT Route annotation
* #Put("/tables")
*/
public function putTableAction(Request $request)
{
$em = $this->getDoctrine()->getManager('psi_db');
$serializer = $this->container->get('jms_serializer');
$dataJson = $request->query->get('table');
$table = $serializer->deserialize($dataJson, Table::class, 'json');
// Here, my $table has no id (that's ok), the TableNode subentity has no id (ok) and my Node subentity already have an id (because they come from the db)
$em->persist($table);
// Here, my $table has a new id (ok), my TableNode has a new id (ok) BUT my Node subentity have a NEW id, so it will be duplicated
$em->flush();
$view = $this->view();
$view->setData($table);
return $this->handleView($view);
}
I tried to use $em->merge($table) instead of $em->persist($table) and my node subentities keep there own id (so they may not be duplicated within the flush) BUT the table and tableNode have no id (null) and are not persisted.
The only solution I found is to loop through the TableNode entities, retrieve the Node entity from the database and do a tableNode->setNode :
$tns = $table->getTableNodes();
foreach ($tns as $tn) {
$nodeId = $tn->getNode()->getId();
$dbNode = $nodeRepo->find($nodeId);
$tn->setNode($dbNode);
}
But it's not a good solution because I make a db search within a loop and a table could contains more than a hundred of TableNode/Node so it might take a lot of resources.
Does anyone have a cleaner solution ?
Thanks.
edit : add classes
Table :
/**
* Table_
* Doctrine "Table" is a reserved name, so we call it Table_
*
* #ORM\Table(name="psi_table")
* #ORM\Entity(repositoryClass="AppBundle\Repository\Table_Repository")
*
* #ExclusionPolicy("all")
*/
class Table_
{
public function __construct()
{
$this->tNodes = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #Expose
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255, nullable=true)
*
* #Expose
*/
private $name;
/**
* #var \stdClass
*
* #ORM\Column(name="author", type="object", nullable=true)
*
* #Expose
*/
private $author;
/**
* #var \stdClass
*
* #ORM\OneToMany(targetEntity="AppBundle\Entity\TableNode", mappedBy="table", cascade={"persist"})
*
* #Expose
* #Type("ArrayCollection<AppBundle\Entity\TableNode>")
* #SerializedName("tNodes")
*/
private $tNodes;
}
TableNode :
/**
* TableNode
*
* #ORM\Table(name="psi_table_node")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TableNodeRepository")
*
* #ExclusionPolicy("all")
*/
class TableNode
{
public function __construct($table = null, $node = null, $position = null)
{
if($table) $this->table = $table;
if($node) $this->node = $node;
if($position) $this->position = $position;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #Expose
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="position", type="integer")
*
* #Expose
*/
private $position;
/**
* #var string
*
* #ORM\Column(name="groupSocio", type="string", nullable=true)
*
* #Expose
* #SerializedName("groupSocio")
*/
private $groupSocio;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Table_", inversedBy="tNodes", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*
* #Expose
* #Type("AppBundle\Entity\Table_")
*/
private $table;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Node", inversedBy="tables", cascade={"persist", "merge"})
* #ORM\JoinColumn(nullable=false)
*
* #Expose
* #Type("AppBundle\Entity\Node")
*/
private $node;
}
Node :
/**
* TableNode
*
* #ORM\Table(name="psi_table_node")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TableNodeRepository")
*
* #ExclusionPolicy("all")
*/
class TableNode
{
public function __construct($table = null, $node = null, $position = null)
{
if($table) $this->table = $table;
if($node) $this->node = $node;
if($position) $this->position = $position;
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
* #Expose
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="position", type="integer")
*
* #Expose
*/
private $position;
/**
* #var string
*
* #ORM\Column(name="groupSocio", type="string", nullable=true)
*
* #Expose
* #SerializedName("groupSocio")
*/
private $groupSocio;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Table_", inversedBy="tNodes", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*
* #Expose
* #Type("AppBundle\Entity\Table_")
*/
private $table;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Node", inversedBy="tables", cascade={"persist", "merge"})
* #ORM\JoinColumn(nullable=false)
*
* #Expose
* #Type("AppBundle\Entity\Node")
*/
private $node;
}
Submitted data (example) :
{"tNodes":[{"id":0,"position":0,"groupSocio":"group1","node":{"id":683,"frontId":"1502726228584","level":"synusy","repository":"baseveg","name":"A synusy from my Angular app!","geoJson":{"type":"FeatureCollection","features":[{"type":"Feature","properties":[],"geometry":{"type":"Point","coordinates":[-10.0634765625,42.0982224112]}}]},"lft":1,"lvl":0,"rgt":2,"children":[{"id":684,"frontId":"1502726228586","level":"idiotaxon","repository":"baseflor","name":"poa annua","coef":"1","geoJson":{"type":"FeatureCollection","features":[{"type":"Feature","properties":[],"geometry":{"type":"Point","coordinates":[-10.0634765625,42.0982224112]}}]},"lft":1,"lvl":0,"rgt":2,"validations":[{"id":171,"repository":"baseflor","repositoryIdTaxo":"7075","repositoryIdNomen":"50284","inputName":"poa annua","validatedName":"Poa annua L."}]}],"validations":[]}}]}
The purpose putTableAction is to:
create new instances of Table_
create new instance of TableNode
do nothing with Node
It means that:
1.You do not need to submit any details of Node. Id field is enough:
{"tNodes":[{"id":0,"position":0,"groupSocio":"group1","nodeId": 683}]}
2.You can add one more field to TableNode, called $nodeId, and map it with "node" field in DB. The purpose of this field is to simplify deserialization, in all other places you can use $node field.
/**
* #var integer
*
* #ORM\Column(name="node", type="integer")
*
* #Expose
*/
private $nodeId;
I want to set id manual I write this code in my Test entity:
can I use setId() for entities like my code?
My code is here:
/**
* Test
* #ORM\Table(name="test")
*/
class Test
{
/**
* #var int
* #ORM\Column(name="id", type="integer")
*/
private $id;
/**
* #var string
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Set id
* #param integer $id
* #return Test
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
* #return integer
*/
public function getId()
{
return $this->id;
}
// other methods
}
is this correct way to set id?
if not what is the correct and standard way?
You can use your own primary key, telling to Doctrine not to generate value ...
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_generatedvalue
/**
* Test
* #ORM\Table(name="test")
*/
class Test
{
/**
* #var int
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
* #ORM\Column(name="id", type="integer")
*/
private $id;
/**
* Set id
* #param integer $id
* #return Test
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
Don't forget setId before persist!
Doctrine expects the primary key of your entity to be immutable (non-changeable) after the entity is persisted/flushed to the database (or fetched from DB).
The code you wrote is perfectly correct in terms of PHP but will most likely break doctrine functionality if you ever use setId().
If you are interested in the internals, look up "Doctrine identity maps"
this is my entity:
/**
* #ORM\Table(name="Animal")
* #ORM\HasLifecycleCallbacks
*/
class Animal {
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var localizedcontent $lctitle
*
* #ORM\ManyToOne(targetEntity="localizedcontent",fetch="EAGER", cascade={"persist"})
* #ORM\JoinColumn(name="lcTitle", referencedColumnName="pkId", nullable=false)
*/
private $lctitle;
/**
* #var localizedcontent $lcdescription
*
* #ORM\ManyToOne(targetEntity="localizedcontent",fetch="EAGER", cascade={"persist"})
* #ORM\JoinColumn(name="lcDescription", referencedColumnName="pkId", nullable=false)
*/
private $lcdescription;
/**
* #ORM\PostLoad
*/
public function postLoad(){
$lct = $this->lctitle;
$lcd = $this->lcdescription;
}
This is my dql:
SELECT a,lct FROM Animal JOIN e.lctitle lct WHERE a.id=:id
When i'm starting xdebug, it tells me that lcdescription is a proxy object and lctitle doesn't exists. I don't know why.
I think the postLoad event is too early because the localizedcontent isn't loaded at this moment, right? Is there an other listener for reading the value of lctitle in relation to the Animal Object?
Thanks
Doctrine always returns proxies. These classes inherit from the entity-classes. It might help if you declare your relations protected instead of private.
/**
* #var localizedcontent $lctitle
*
* #ORM\ManyToOne(targetEntity="localizedcontent",fetch="EAGER", cascade={"persist"})
* #ORM\JoinColumn(name="lcTitle", referencedColumnName="pkId", nullable=false)
*/
protected $lctitle;
or you could write a getter and call this one in your post-load function
public function getLctitle() {
return $this->lctitle;
}
public function getLcdescription() {
return $this->lcdescription;
}
/**
* #ORM\PostLoad
*/
public function postLoad(){
$lct = $this->getLctitle();
$lcd = $this->getLcdescription();
}
Here's what I'm having trouble with.
I've a Table which contains a column called shown_on_homepage and only one row should be set to 1, the rest should all be set to 0. I'm trying to add a new row to the database and this one should be set to 1, setting the one that previously had a 1 to 0.
In MySQL I know this can be achieved by issuing an update before the insert:
UPDATE table_name SET shown_on_homepage = 0
Here's my Entity:
class FeaturedPerson {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="content", type="string", length=2500, nullable=false)
*/
private $content;
/**
* #var \DateTime
*
* #ORM\Column(name="date_updated", type="datetime")
*/
private $dateUpdated;
/**
* #var bool
*
* #ORM\Column(name="shown_on_homepage", type="boolean", nullable=false)
*/
private $isShownOnHomepage;
//...
public function getIsShownOnHomepage() {
return $this->isShownOnHomepage;
}
public function setIsShownOnHomepage($isShownOnHomepage) {
$this->isShownOnHomepage = $isShownOnHomepage;
return $this;
}
}
And for the Controller I've:
$featured = new FeaturedPerson();
$featured->setContent('Test content.');
$featured->setDateUpdated('01/02/2013.');
$featured->setIsShownOnHomepage(TRUE);
$em = $this->getDoctrine()->getManager();
$em->persist($featured);
$em->flush();
It does add the new row, but the one that had a shown_on_homepage set to 1 still has it. I've researched but I couldn't find a way to achieve this, I hope you can help me.
You could execute a query prior to your existing code in your controller:
$queryBuilder = $this->getDoctrine()->getRepository('YourBundleName:FeaturedPerson')->createQueryBuilder('qb');
$result = $queryBuilder->update('YourBundleName:FeaturedPerson', 'd')
->set('d.isShownOnHomepage', $queryBuilder->expr()->literal(0))
->where('d.isShownOnHomepage = :shown')
->setParameter('shown', 1)
->getQuery()
->execute();
Change 'YourBundleName' to your bundle name.