问题
My code is:
$query = $em->createQuery("UPDATE AppBundle:Project u SET u.name=1, u.key=?2, u.leader=?3 WHERE u.id = ?4");
$query->setParameter(1, $project->name);
$query->setParameter(2, $project->key);
$query->setParameter(3, $project->lead->name);
$query->setParameter(4, $project->id);
$result = $query->getResult();
Now when I run it, it gives me a error:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key = 'EIAD', leader = 'fake.name' WHERE id = '12305'' at line 1
I cant figure out what I'm doing wrong here. I even tried with the Object update like:
$project->setname();
etc.
EDIT: Forgot to say the code is used in a self created command!
回答1:
Using Querybuilder. Example:
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository(Project::class)->createQueryBuilder('')
->update(Project::class, 'u')
->set('u.name', ':name')
->set('u.key', ':key')
->set('u.leader', ':leader')
->setParameter('name', $project->name)
->setParameter('key', $project->key)
->setParameter('leader', $project->leader)
->where('u.id = :id')
->setParameter('id', $project->id)
->getQuery();
$result = $query->execute();
回答2:
The properties of Entities are private or protected. This means you cannot access them directly like this: $project->name
you have to use the getters and setters like this: $project->getName()
来源:https://stackoverflow.com/questions/45978280/symfony-doctrine-update-query-fail