【问题标题】:concatenate result from getRepository symfony连接来自 getRepository symfony 的结果
【发布时间】:2017-10-09 21:29:05
【问题描述】:

有一种方法可以连接 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']
    ]);
}

【问题讨论】:

  • 添加示例输入和输出。
  • 我不认为->findOneById($id)(除非你以不同的方式实现它,它与->find($id) 相同)做你认为它做的事情。
  • 不,不是……

标签: symfony


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    相关资源
    最近更新 更多