I\'m trying to learn Symfony. Today I was following The associations tutorial. I decided to make a small application that a House, Kitchens, Bedrooms, and cabinets. I (tried to
There are several minor problems in your code, more on that later.
Here is \App\Repository\CabinetRepository::findByBedroom:
public function findByBedroom(Bedroom $bedroom) //use joins??
{
return $this->createQueryBuilder('cabinet')
->join('cabinet.kitchen', 'kitchen')
->join('kitchen.house', 'house')
->join('house.bedroom', 'bedroom')
->addSelect('cabinet')
->andWhere('bedroom = :bedroom')
->setParameter('bedroom', $bedroom)
->getQuery()
->getResult();
}
For bedroom entity with ID 815 the code above returns the following (formatted as symfony/var-dumper would do that):
array:2 [▼
0 => Cabinet {#387 ▼
-id: 88
-shopUrl: "co.m"
-account_id: null
-kitchen: Kitchen {#354 ▼
+__isInitialized__: false
-cabinet: null
-house: null
-id: 2
-name: null
…2
}
}
1 => Cabinet {#364 ▼
-id: 1
-shopUrl: "ur.l "
-account_id: null
-kitchen: Kitchen {#370 ▼
+__isInitialized__: false
-cabinet: null
-house: null
-id: 55
-name: null
…2
}
}
]
Note: house references are null because of lazy loading.
So, small problems in your code:
Your query in CabinerRepository was doing wrong joins. For correct joins see code above.
That query referring to unknown field time
. I have removed that reference.
And also was using bedroom ID instead of bedroom entity.
Your Kitchen.php is incomplete, it refers Collection and ArrayCollection classes, but there are no corresponding use
directives. Just add this after namespace
before class
:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
Update: here is how to get repository reference:
public function myControllerAction(/* other parameters */, CabinetRepository $cabRepo)
{
$cabinet = $cabRepo->find($id);
// OR, if you don't want to add parameter for some reason:
$cabRepo = $this->getDoctrine()->getRepository(Cabinet::class);
$cabinet = $cabRepo->find($id);
}