Doctrine 2, one to many relationship OrderBy Annotations - doctrine-orm

Hello I have got this php order by annotations on my one to many relationship
/**
* TaskCategory
*
* #Table(name="task_category")
* #Entity(repositoryClass="models\Repositories\TaskCategoryRepository")
*/
class TaskCategory
{
/**
* #var array $tasks
*
* #OneToMany(targetEntity="Task", mappedBy="taskCategory"")
* #OrderBy({"sort_order" = "ASC"})
*/
private $tasks;
And I got this error:
Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message '[Syntax Error] Expected Doctrine\Common\Annotations\Lexer::T_CLOSE_PARENTHESIS, got 'order' at position 108
Anyone got similar issue? Any advise will be greatly appreciated.

The correct annotation is
#OrderBy({"name" = "ASC"})
See: Doctrine 2 manual: Annotations reference

oops sorry I think I know the mistake it it's the double quote
#OneToMany(targetEntity="Task", mappedBy="taskCategory"")
suppose to be
#OneToMany(targetEntity="Task", mappedBy="taskCategory")
thanks for the answer anyway.

Related

The database schema is not in sync with the current mapping file (but it is !)

I just fixed some things in my code. I'm now trying to validate my schema
php bin/console doctrine:schema:validate
Doctrine tells me my mapping is correct but my database schema is not. So I'm doing a
schema:update --dump-sql
which results in the same ALTER again and again, that I already performed many times.
Here is the ALTER :
ALTER TABLE migration_versions CHANGE version version VARCHAR(14) NOT NULL;
I did it (with --force), the entity is reflecting the change already :
**
* MigrationVersions
*
* #ORM\Table(name="migration_versions")
* #ORM\Entity
*/
class MigrationVersions
{
/**
* #var string
*
* #ORM\Column(name="version", type="string", length=14, nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $version;
I am correct right ? its varchar, lenght 14...
And so is it in my database
I don't think Im making a mistake here but I may be missing something.
Have you already verified that the server_version in the doctrine config file is correct? (config/packages/doctrine.yaml in symfony5)
It happened to me that I was using MariaDB (version 10.4.11-MariaDB - Source distribution) and in the file doctrine.yaml the server_version parameter had the value 5.7.
After I corrected that, the error no longer occurred.
Also you can check this question

Symfony 4: Updating an existing entity through a deserialized entity ends up with a new related item or with an ORMInvalidArgumentException

That's my first question here on Stackoverflow.com and before I'll write to much. First the controller function:
/**
* #Rest\Patch("/identifiers/v2/{id}")
*
* #ParamConverter("identifier")
* #ParamConverter("identifierPatch", converter="fos_rest.request_body")
*/
public function patchAction(Identifier $identifier, Identifier $identifierPatch)
{
$identifier->setLandingPage($identifierPatch->getLandingPage());
$identifier->setIdentifier($identifierPatch->getIdentifier());
$identifier->setIsUsed($identifierPatch->getIsUsed());
$this->entityManager->flush();
/**
* Just for debugging...
*/
$view = $this->view([
'identifier' => $identifier,
'identifierPatch' => $identifierPatch
]);
return $this->handleView($view);
}
When i try to UPDATE an existing entity this way I get an ORMInvalidArgumentException with a message "A new entity was found through the relationship (...)"
When I set cascade={"persist"} on the related entity:
/**
* #ORM\ManyToOne(targetEntity="App\Entity\LandingPage", inversedBy="identifiers")
* #ORM\JoinColumn(nullable=false)
* #Assert\NotNull()
* #Serializer\Type("App\Entity\LandingPage")
*/
private $landing_page;
... the related entity will be inserted as new entity and that's not what I am looking for.
I could use $this->entityManager->merge($identifier) but that's not what I am looking for aswell, because I'll need to do some manual validations in future and I would like to return the entity as response (the related entity will be null when not updated) and $this->entityManager->merge() will be deprecated in Doctrine 3.
Question: Is there any way to update the given entity with the deserialized entity?
Greetings,
Danny Endert
EDIT (1):
Well, I guess i found a solution regarding this "issue".
services.yaml
jms_serializer.object_constructor:
alias: jms_serializer.doctrine_object_constructor
public: false
Now I'm not getting any exception and the related entity will not be inserted as new entity.

Doctrine 2 not creating foreign key

I have this piece of code inside an Entity:
/**
* #ORM\ManyToOne(targetEntity="Centers")
* #ORM\JoinColumn(name="center_id", referencedColumnName="id")
* #ORM\Column(type="string", length=36, name="center_id")
*/
protected $centerId;
However, schema:update says that all is in sync. Even changing Centers to some other inexistent word, produces no error.
Please delete the last line of annotation doctrine like this and change $centerId by $center (there is object an object) :
/**
* #ORM\ManyToOne(targetEntity="Centers")
* #ORM\JoinColumn(name="center_id", referencedColumnName="id")
*/
protected $center;
Clear cache and run your command.
Tell me if this solved your problem.

update createdAt & updatedAt fields automatically in symfony3 (doctrine)

I have an entity (Server) that should have two extra fields: createdAt and updatedAt (like cakephp). I tried this on Server entity:
/**
* #ORM\PrePersist
* #ORM\PreUpdate
*/
public function updateTimestamp()
{
$this->setModifiedAt(new \DateTime());
if($this->getCreatedAt() == null){
$this->setCreatedAt(new \DateTime());
}
}
but nothing happened during update process. Then I searched about it and there was this EventListener solution.
I couldn't fix it by that too.
is there any solution for this problem, please provide a step by step solution.
thank you a lot and sorry for bad English! ;)
Check you have the HasLifecycleCallbacks annotation on your entity, as example:
/**
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Server
Hope this help

Issue with persisting specific relation with Doctrine2 ODM

I am using Doctrine 2 MongoDB ODM, all working fine except 1 specific relation. What's obscure is that I have seemingly identical relations in the project and they all work just fine
namespace Project\Entities\World; // same NS as class, but this is after
// splitting functionality from Entity to MappedSuperclass, didn't work either
/**
* #ReferenceOne(targetDocument="Project\Entities\World")
* #var IWorld
*/
protected $world;
used in Project\Entities\PlayerCharacter (extends Project\Entities\World\Object mentioned above)
=>
namespace Project\Entities;
/**
* #Document(collection="worlds")
* #HasLifecycleCallbacks
*/
class World {
/**
* #ReferenceMany(targetDocument="PlayerCharacter")
* #var ArrayCollection
*/
protected $playerCharacters;
}
When I set the $world variable, it's fine in the PHP script. Even $objectManager->refresh($character), $character->getWorld() === $world turns out fine. But it does never appear in the database itself (die right after setting it and flush to make sure it is never changed by accident somewhere) on the PlayerCharacter's end, only on the World side
On the other hand
class PlayerCharacter {
/**
* #ReferenceOne(targetDocument="User")
* #var User
*/
protected $user;
}
=>
/**
* #Document(collection="users")
* #HasLifecycleCallbacks
*/
class User {
/**
* #ReferenceMany(targetDocument="PlayerCharacter")
* #var ArrayCollection
*/
protected $characters;
}
works
In simplified version:
- PlayerCharacter::$user <==(1:N)==> User::$characters
(and all others) are fine, while only
- PlayerCharacter::$world <==(1:N)==> World::$playerCharacters
works only on the World side
Looking at it many days, can't find anything different.
Tried renaming property names, no change
Hydrator entry for character--->world looks identically to others
When I add the entry semi-manually (via RockMongo), it works fine
Creating the "world" field as NULL makes no difference, with {} it says "Undefined index: $id", but I guess that's an expected behaviour
Entities separately work very fine too, it really just is this one relation
Is there anything I am missing/overlooked or what can I do to discover why is it not getting persisted
(will edit the post if there's need for more info)
Thank you!
Ok, the thing was there were many entries in the UoW some containing World => null and some World => ...WorldProxy, so the latter probably got overwritten
Using flush() before the assignment solved this