I have self-referencing menu entity (created using make:entity
):
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Menu", inversedBy="children")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Menu", mappedBy="parent")
*/
private $children;
and the data:
| id | name | parent |
|----|-----------|--------|
| 1 | MainItem | null |
| 2 | Child 1-1 | 1 |
| 3 | Child 1-2 | 1 |
| 4 | Child 1-3 | 1 |
My function to get the top-level menu items:
private function getTopMenu (MenuRepository $menuRepository) {
return $menuRepository->findBy(['parent' => null]);
}
returns the following:
array:1 [▼
0 => Menu^ {#1186 ▼
-id: 1
-name: "MainItem"
-parent: null
-children: PersistentCollection^ {#1188 ▼
-snapshot: []
-owner: Menu^ {#1186}
-association: array:15 [ …15]
-em: EntityManager^ {#1050 …11}
-backRefFieldName: "parent"
-typeClass: ClassMetadata {#1096 …}
-isDirty: false
#collection: ArrayCollection^ {#1189 ▼
-elements: []
}
#initialized: false
}
}
]
Because I wasn't getting anything in the children, I tried working backwards using $menuRepository->find(2)->getParent();
which returned:
Menu^ {#1205 ▼
+__isInitialized__: false
-id: 1
-name: null
-parent: null
-children: null
…2
}
Lastly I tried $menuRepository->find(2)->setParent($menuRepository->find(3))->getParent()
which finally seemed to get me somewhere:
Menu^ {#1201 ▼
-id: 3
-name: "Child 1-2"
-parent: Menu^ {#1205 ▶}
-children: PersistentCollection^ {#1200 ▶}
}
I can't figure out why getChildren
and getParent
aren't returning the data.