I'm trying to use the EntityManager to load all fields from a table as well as its associations, here's my (test) scenario: I have the entity user and the entity user_post, and the user can have several user_post.
user:
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity */
class user
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="bigint")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
public $id;
/**
* @ORM\OneToMany(targetEntity="user_post", mappedBy="id_user", cascade={"persist", "remove"}, orphanRemoval=TRUE, fetch="EAGER")
*/
public $posts;
/**
* @var string $author
*
* @ORM\Column(name="author", type="string", length=100, nullable=false)
*/
public $author;
/**
* @var text $content
*
* @ORM\Column(name="content", type="text", nullable=false)
*/
public $content;
/**
* @var text $createdAt
*
* @ORM\Column(name="created_at", type="text", nullable=false)
*/
public $createdAt;
public function __construct() {
$this->posts = new ArrayCollection();
}
}
user_post:
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity */
class user_post
{
/**
* @var integer $id
*
* @ORM\Column(name="id", type="bigint")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
public $id;
/**
* @var integer $id_user
*
* @ORM\ManyToOne(targetEntity="user", inversedBy="posts")
* @ORM\JoinColumn(name="id_user", referencedColumnName="id", nullable=FALSE)
*/
public $id_user;
/**
* @var text $content
*
* @ORM\Column(name="content", type="text", nullable=false)
*/
public $content;
}
I'm using public variables to be easier to debug.
Now, I'm trying:
$user = $doctrine->em->find('user', 2);
I get the user object ok, however instead the user_post object it returns:
Doctrine\ORM\PersistentCollection Object ( [snapshot:Doctrine\ORM\PersistentCollection:private] => Array ( [0] => user_post Object ( [id] => 1 [id_user] => user Object *RECURSION*
And doesn't return the actual data. Also it returns a giant array.
Is there a way to get all the data with the find function?
Your $posts
property is mapped as a OneToMany
, which means that a user
will have many user_post
.
Therefore $posts
is hydrated as a collection of user_post
objects, which contains the objects you expect:
$user = $doctrine->em->find('user', 2);
foreach ($user->posts as $post) {
echo $post->content;
}