Symfony连接表ManyToMany的最佳实践

时间:2018-02-25 16:50:08

标签: symfony controller many-to-many

我对Symfony(以及一般的PHP)相对较新,我想知道如何完成以下任务:

我有3张桌子:

USER
  - id
  - lastNm
  - firstNm
  - username
  - isActive

COMPANY
  - id
  - name
  - isActive

COMPANY_USER
  - id
  - user
  - company
  - email
  - isActive

我想创建一个rest api。 用户可以使用新公司创建,也可以添加到现有公司。创建公司时,它适用于新用户或现有用户。我需要在COMPANY_USER表中添加几个属性。

我需要哪些控制器以及我将哪些功能放入其中?特别是用于插入,更新和删除记录。

我想到的东西太复杂了,必须有更优雅的方式来做到这一点......

更新:

UserController中:

  /**
   * @Route("/user/add", name="user_add")
   * @Method("POST")
   */
  public function addAction(Request $request, UserPasswordEncoderInterface $passwordEncoder, SerializerInterface $serializer)
  {
    $data = $request->getContent();
    $user = $serializer->deserialize($data, User::class, 'json');
    $em = $this->getDoctrine()->getManager();

    $user->setPassword($passwordEncoder->encodePassword($user, $user->getPassword()));

    $em->persist($user);

    try {
      $em->flush();
    }
    catch (UniqueConstraintViolationException $e) {
      return new Response(
        'Unique constraint',
        Response::HTTP_CONFLICT
      );
    }

    return new Response(
      $serializer->serialize(
        $user,
        'json'),
      Response::HTTP_CREATED
    );
  }

CompanyController:

  /**
   * @Route("/company/add", name="company_add")
   * @Method("POST")
   */
  public function addAction(Request $request, SerializerInterface $serializer)
  {
    $data = $request->getContent();
    $company = $serializer->deserialize($data, Company::class, 'json');
    $em = $this->getDoctrine()->getManager();

    $em->persist($company);

    try {
      $em->flush();
    }
    catch (UniqueConstraintViolationException $e) {
      return new Response(
        'Unique constraint',
        Response::HTTP_CONFLICT
      );
    }


    return new Response(
      $serializer->serialize(
        $company,
        'json'),
      Response::HTTP_CREATED
    );
  }

CompanyUserController的addAction应如何显示?

0 个答案:

没有答案