Symfony 3.4 - 预期实体获得了 EntityManager API REST

Symfony 3.4 - Expected Entity got EntityManager API REST

我正在创建一个 API REST,我想为 $userInterest 设置一个名为 Category 的实体(多对一)我对 User 实体做了同样的事情( 并且我设置了 "Profile" 实体 ),但是 Profile 实体作为参数传递并且它是在此函数中创建,因此它很简单并且有效。

我是这样做的:

/**
 *
 * @Rest\Post(
 *     path = "/users/register",
 *     name = "api_users_add"
 * )
 * @Rest\View(StatusCode=201, serializerGroups={"user_detail"})
 * @ParamConverter(
 *     "user",
 *     converter="fos_rest.request_body",
 *     options={"deserializationContent"={"groups"={"Deserialize"}}},
 * )
 * @ParamConverter(
 *     "profile",
 *     converter="fos_rest.request_body",
 *     options={"deserializationContent"={"groups"={"Deserialize"}}},
 * )
 * @ParamConverter(
 *     "userInterest",
 *     converter="fos_rest.request_body",
 *     options={"deserializationContent"={"groups"={"Deserialize"}}},
 * )
 */
public function postUserAction(Request $request, User $user, Profile 
$profile, UserInterest $userInterest) {

    $profile->setLastConnexion(new \DateTime('now'));
    $profile->setCreatedAccount(new \DateTime('now'));

    $user->setIdProfile($profile);

    $em = $this->getDoctrine()->getManager();
    $em->persist($profile);
    $em->flush();

    $this->encodePassword($user);
    $user->setRoles([User::ROLE_USER]);

    $this->persistUser($user);
 }

-

因此,前面的示例非常有效,但是当我尝试为 $userInterest 设置 Category 实体时,它不起作用( 类别也已创建,就像"static" table) 所以问题是我如何为 $userInterest 设置 Category 知道在前面的示例中实体是在函数中创建的此示例实体已创建,所以我尝试了:

    $em_category = $this->getDoctrine()->getManager();
    $em_category->getRepository('AppBundle:Category')->findOneBy(array('id' => ($request->get('id_category'))));

    $userInterest->setCategory($em_category);

    $em = $this->getDoctrine()->getManager();
    $em->persist($userInterest);
    $em->flush();

但这会导致错误:

"Expected value of type "AppBundle\Entity\Category" for association >field "AppBundle\Entity\UserInterest#$category", got >"Doctrine\ORM\EntityManager" instead."

如何设置实体类别而不是实体管理器...?

已发送JSON(如果有帮助):

{
"username": "Usertest",
"password": "strenghtpassword",
"email": "thxforall@symfony.com",
"birth": "1999-04-26T18:25:43-05:00",
"content": "I like Netflix",
"id_category": "1"
}

在类别table中,例如ID:1作为内容"what do you like"。

这是因为您从未将 $em_catagory 分配给 findOneBy,它仍然是一个实体管理器对象。试试这个:

$em_category = $this->getDoctrine()->getManager();
$category = $em_category->getRepository('AppBundle:Category')->findOneBy(array('id' => ($request->get('id_category'))));

$userInterest->setCategory($category);

$em = $this->getDoctrine()->getManager();
$em->persist($userInterest);
$em->flush();