使用Symfony 2.8框架在动态实体收集器中联接表

时间:2018-07-11 09:02:24

标签: symfony doctrine query-builder

在这种情况下,我得到了一个Product数组。产品链接到类别。类别没有自己的数组,但紧跟产品类别。

使用的框架是Symfony 2.8

电流输出

   array(1) {
      [0]=>
      array(3) {
        [0]=>
        array(26) {
          ["id"]=>
          int(902)
          ["articleNumber"]=>
          string(8) "32132435"
          ["name"]=>
          string(31) "Sensa Umbria 105 LTD 2017 Heren"
        }
        ["id"]=>
        int(18)
        ["name"]=>
        string(12) "Aanbiedingen"
      }
    }

想要的输出

  array(1) {
      [0]=>
      array(3) {
        [0]=>
        array(26) {
          ["id"]=>
          int(902)
          ["articleNumber"]=>
          string(8) "32132435"
          ["name"]=>
          string(31) "Sensa Umbria 105 LTD 2017 Heren"
          ["category"]=> array(2) {
              ["id"]=>
              int(18)
              ["name"]=>
              string(12) "Aanbiedingen"
          }
        }
      }
    }

当前功能

private $allowedEntities = [
    'product' => 'CasProductBundle:Product',
    'project' => 'CasProjectBundle:Project',
];

private $activeFields = [
    'active',
    'isActive'
];

private $delFields = [
    'deleted',
    'isDeleted'
];

public function getEntityAction()
{
    $defaults = [
        'showNonActive' => true,
        'showDeleted' => false
    ];

    $params = array_merge($defaults, $_POST);

    if (!isset($params['entity']))
        throw new NotFoundHttpException('No entity given');

    if (!array_key_exists($params['entity'], $this->allowedEntities))
        throw new NotFoundHttpException('Entity is not allowed');

    $entityShortName = $this->allowedEntities[$params['entity']];
    $entityShortNameArr = explode(":", $entityShortName);
    $bundle = $this->get('kernel')->getBundle($entityShortNameArr[0], true);
    $entityNamespace = $bundle->getNamespace() . '\Entity\\' . $entityShortNameArr[1];

    $repository = $this->getDoctrine()->getRepository($this->allowedEntities[$params['entity']]);

    /** @var QueryBuilder $qb */
    $qb = $repository->createQueryBuilder('p');

    if (isset($params['fields'])) {
        $temp = ''; $i = 0;
        foreach ($params['fields'] as $field) {
            $temp .= ($i != 0 ? ', ' : '') . 'p.' . $field;
            $i++;
        }
        $qb->select($temp);
    }

    if (isset($params['join'])) {
        foreach ($params['join'] as $table => $fields) {
            $temp = ''; $i = 0;
            foreach ($fields as $field) {
                $temp .= ($i != 0 ? ', ' : '') . strtolower($table) . '.' . $field;
                $i++;
            }
            $qb->addSelect($temp);
            $qb->innerJoin('p.' . $table, strtolower($table));
        }
    }

    $i = 0;
    if (!$params['showDeleted']) {
        foreach ($this->delFields as $field) {
            if (property_exists($entityNamespace, $field)) {
                $qb->{($i == 0 ? 'where' : 'andWhere')}('p.' . $field . ' = 0');
                $i++; break;
            }
        }
    }

    if (!$params['showNonActive']) {
        foreach ($this->activeFields as $field) {
            if (property_exists($entityNamespace, $field)) {
                $qb->{($i == 0 ? 'where' : 'andWhere')}('p.' . $field . ' = 1');
                $i++; break;
            }
        }
    }

    if (isset($params['filters'])) {
        foreach ($params['filters'] as $key => $filter) {
            $qb
                ->andWhere('p.' . $key . (is_array($filter) ? ' IN (:filter)' : ' = :filter'))
                ->setParameter('filter', $filter);
        }
    }

    if (isset($params['sort'])) {
        $i = 0;
        foreach ($params['sort'] as $field => $sort) {
            $qb
                ->{($i == 0 ? 'orderBy' : 'addOrderBy')}('p.' . $field, $sort);
            $i++;
        }
    }

    if (isset($params['limit'])) {
        $qb->setMaxResults($params['limit']);
    }

    if (isset($params['offset'])) {
        $qb->setFirstResult($params['offset']);
    }

    $entities = $qb
        ->getQuery()
        ->getArrayResult()
    ;

    return new JsonResponse($entities);
}

这些是我可以传递给函数的所有参数。

- entity =>
    "product"

- showNonActive => (default: false)
    true

- showDeleted => (default: false)
    true

- limit =>
    5

- offset =>
    10

- filters =>
    'id' => 28
    or
    'id' => [7, 8, 9]

- sort =>
    ['id' => 'ASC', 'createDate' => 'DESC']

- fields =>
    ['id', 'name', 'createDate']

- join =>
    [
       'categories' => ['id', 'name']
    ]

1 个答案:

答案 0 :(得分:0)

您的查询构建似乎有点复杂,但您可以尝试使用partial从原则中进行选择吗?

简化版本可能如下所示:

$qb->select('partial p.{id, articleNumber, name}') ->addSelect('partial c.{id, name}') ->from('...:Product', 'p') ->innerJoin('p.category', 'c');

添加where子句,排序等,并以相同的方式获得结果:

$entities = $qb ->getQuery() ->getArrayResult() ;

请记住,这可能会有一些副作用:{{3}}。