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

问题描述 投票:0回答:1

在这种情况下我得到了一个 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']
    ]
php symfony doctrine query-builder
1个回答
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()
    ;

请记住,这可能会产生一些副作用:链接

© www.soinside.com 2019 - 2024. All rights reserved.