Self Join Query Doctrine 2 Zendframework 2

时间:2013-09-12 15:09:26

标签: doctrine-orm zend-framework2

我正在使用Doctrine 2 ORM,Zendframework 2

角色实体中的实体属性如下所示

/**
     *
     * @ORM\Column(type="string")
     */
    protected $name;

   /**
     *
     * @ORM\OneToMany(targetEntity="\Application\Entity\Role", mappedBy="parent")
     */
    protected $children;

    /**
     *
     * @ORM\ManyToOne(targetEntity="\Application\Entity\Role", inversedBy="children")
     * 
     */
    protected $parent;

Mysql表看起来像这样。

enter image description here

我正在寻找的结果是一个数组。 有一件事是至关重要的,必须在apprearing value之前将数组中的任何条目添加为键, 所以订单非常重要。

即[site-manager] =>如果[guest] => guest不能作为第一个条目(0索引)来因为guest(value)在数组中不存在作为键,所以它不会存在 所以[客人] =>即使在表格

中输入第二条记录,它也会先到
Array(
[guest] => 
[site-manager] => guest
[company-manager] => site-manager
[member] => guest
[staff] => member
[internalstaff] => member
[sales] => staff
[manager] => sales,internalstaff
[admin] => manager
)

我在我的控制器中运行此代码,该控制器返回空数组

$qb = $objectManager->createQueryBuilder();
        $qb->select('r, p')
                ->from('\Application\Entity\Role', 'r')
                ->innerJoin('r.parent','p', 'with','p.id = r.id')
                //->where('b.id = ?1')
                ->orderBy('r.id', 'ASC');

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

一种解决方案可能是

    $qb = $objectManager->createQueryBuilder();
            $qb->select('r.name', 'c.name as children')
                    ->from('\Application\Entity\Role', 'r')
                    ->join('r.parent','c');

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

            $refine =  array();
            foreach ($data as $v)
            {
                if(is_array($v))
                {
                    if(array_key_exists($v["children"], $refine)){
                        $refine[$v["name"]][] = $v["children"];    
                    } else {
                        $refine[$v["children"]] = array();    
                        $refine[$v["name"]][] = $v["children"];    
                    }

                }

            }
 print_r($refine);

将返回以下

Array
(
    [guest] => Array
        (
        )

    [site-manager] => Array
        (
            [0] => guest
        )

    [company-manager] => Array
        (
            [0] => site-manager
        )

    [member] => Array
        (
            [0] => guest
        )

    [staff] => Array
        (
            [0] => member
        )

    [internalStaff] => Array
        (
            [0] => member
        )

    [sales] => Array
        (
            [0] => staff
        )

    [manager] => Array
        (
            [0] => internalStaff
            [1] => sales
        )

    [admin] => Array
        (
            [0] => manager
        )

)

如果您希望展平内部阵列

,可以使用implode功能