连接getRepository symfony的结果

时间:2017-10-09 21:29:06

标签: symfony

有一种方法可以连接symfony中的findBy操作的两个结果吗?如果产品是由用户创建的,我尝试将用户对象连接到产品数组。我的代码:

public function indexAction()
{
    $products = $this->getDoctrine()
        ->getRepository('AppBundle:Product')
        ->findById($this->getUser()->getId());

    if ($products[0]->getCreatedByUser() == 1){
         $userDetails = $this->getDoctrine()->getRepository('AppBundle:User')
        ->findOneById($product->getUserId());

    //here somehow to concatenate the value from $user to the $products array
    }

    return $this->json($products, Response::HTTP_OK, [], [
        'groups' => ['products']
    ]);
}

1 个答案:

答案 0 :(得分:0)

您可以创建一个对象,该对象包含指向$ user和$ products数组的值的指针。或者,您可以使用(value,key)创建一个数组来映射依赖项。

但是你为什么要在控制器级别上这样做呢?

创建数据库(oneToOne)关系不是更好吗?通过这种方式,您可以查询产品,它也会加载userDetails。然后,您可以使用例如:{{ products.product.userDetails.username }}访问twigview中的userDetails,而无需在控制器中使用任何业务逻辑。