Reputation: 4114
I am new to Symfony. I want to create a blog site. So for that I have created two entities post and user. I think I have also relate both the entities properly as described over here:
http://symfony.com/doc/current/doctrine/associations.html
AppBundle/Entity/Post.php:
...
/**
* Post
*
* @ORM\Table(name="post")
* @ORM\Entity(repositoryClass="AppBundle\Repository\PostRepository")
*/
class Post
{ /**
* @ORM\ManyToOne(targetEntity="User", inversedBy="post")
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $user;
....
}
AppBundle/Entity/User.php:
...
/**
* User
*
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
*/
class User extends BaseUser
{
/**
* @ORM\OneToMany(targetEntity="Post", mappedBy="user")
*/
private $post;
...
}
I'm successfully able to save the a post with its userid(user who creates the post). But I'm not able to achieve the reverse of this. i.e get all the posts created by an user. I'm trying to achieve it like this:
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')->find($this->getUser()->getId());
dump($user->getPost());exit;
But I'm not getting any posts in the variable. (FYI: There are posts in the database with the user id). Here is what I'm getting for above:
PostController.php on line 163:
PersistentCollection {#103 ▼
-snapshot: []
-owner: User {#76 ▶}
-association: array:15 [ …15]
-em: EntityManager {#374 …11}
-backRefFieldName: "user"
-typeClass: ClassMetadata {#80 …}
-isDirty: false
#collection: ArrayCollection {#102 ▼
-elements: []
}
#initialized: false
}
Note: I'm using FosUserBundle for user management. Not sure if it is making issues over here.
Any help would be appreciated.
Thanks,
Parth vora
Upvotes: 2
Views: 1485
Reputation: 4114
I got the issue here. All above code is correct. I was just forgetting to call one method to get all the posts created by an user.
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('AppBundle:User')->find($this->getUser()->getId());
dump($user->getPost()->getValues());exit;
getValues() is the method to extract the data from the PersistentCollection class.
PS: Symfony's documentation needs a huge improvement. :(
Thanks,
Parth vora
Upvotes: 2