Reputation: 502
I have two entities: Review
and User
. There is a user's OneToMany relationship in User
entity:
/**
* @ORM\OneToMany(targetEntity="Review", mappedBy="owner")
*/
protected $reviews;
public function __construct() {
parent::__construct();
$this->reviews = new \Doctrine\Common\Collections\ArrayCollection();
}
And connection in Review
entity looks like below:
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="reviews")
* @ORM\JoinColumn(name="owner_id", referencedColumnName="id")
*/
private $owner;
In a controller, I am trying to get all the reviews for logged user. So I am using a getReviews()
getter generated from console.
/**
* @Route("/dashboard")
*/
public function dashboardShow() {
$user = new User();
$reviews = $user->getReviews();
return $this->render('dashboard.html.twig', array(
'reviews' => $reviews
));
}
But $reviews
seems empty, when i dump it, I get: object(Doctrine\Common\Collections\ArrayCollection)#285 (1) { ["elements":"Doctrine\Common\Collections\ArrayCollection":private]=> array(0) { } }
Tables in database are populated. Could any one of you point me what I'm missing?
Upvotes: 1
Views: 2204
Reputation: 337
yes it's empty, because collection is not initialized (in dump there is also "#initialized: false")
how to initialize a collection? there are more ways how to do it:
call
$user->getReviews()->count()
or make custom SQL function in the repository
$this->createQueryBuilder('user')
->select('user, reviews')
->leftJoin('user.review', 'reviews')
->getQuery()->getResult();
Upvotes: 3
Reputation: 9362
You need to first retrieve the logged in user and then load their related entity.
/**
* @Route("/dashboard")
*/
public function dashboardShow() {
// Pulls the currently authenticated user from symfony internals
$user = $this->getUser();
// If your authentication provider already pulls this entity from the database
// you can skip this step and just use $user->getReviews(); below.
$userEntity = $this->get('doctrine')
->getManager()
->getRepository('NamespacedBundle:User')
->findOne($user->getId());
$reviews = $userEntity->getReviews();
return $this->render('dashboard.html.twig', array(
'reviews' => $reviews
));
}
Upvotes: 1