我想在一个控制器中解决插入/更新问题。这是我的代码:
public function setOwnershipAction(Request $request) {
$session = $this->get('security.context')->getToken()->getUser();
$em = $this->getDoctrine()->getManager();
$game = $em->getRepository('GameShelfGamesBundle:Game')->find($request->request->get('hash'));
$user = $em->getRepository('GameShelfUsersBundle:User')->find($session->getId());
$typo = $em->getRepository('GameShelfUsersBundle:OwnState')->find($request->request->get('setownstate')['id']);
$plat = $em->getRepository('GameShelfGamesBundle:Platforms')->find($request->request->get('platformown')['id']);
$check = $em->getRepository('GameShelfUsersBundle:Own')->findBy(array(
'user' => $user,
'game' => $game
));
if(!$check) {
$own = new Own;
$own->setGame($game);
$own->setUser($user);
$own->setTypo($typo);
$own->setPlatforms($plat);
$own->setUpdated(date("Y-m-d H:i:s"));
$em->persist($own);
$em->flush();
} else {
$check->setTypo($typo);
$em->flush();
}
}
现在,insert(在if(!$check)
变为true之后)可以正常工作,但在else
之后它不会单击。我的错误是Fatal error: Call to a member function setTypo() on a non-object
。
答案 0 :(得分:3)
findBy()
方法将返回一个数组。您需要使用findOneBy()
,或循环浏览findBy()
结果。