Let's say I've got an entity called User
with some properties like firstName, lastName, age
and collection of Posts
.
Is there a way to load this User
entity with the EntityManager
and Find
-method without loading all properties/collections?
I'm using a REST API
to retrieve the User
and I want to seperate the calls:
- api/user/1 - should retrieve the
User
object with onlyfirstName, lastName and age
. - api/user/1/posts - should retrieve the
User
object with the properties and a collection ofPosts
.
I know I can use QueryBuilder
and create seperate methods to retrieve the desired data, but I want to have it this way:
The scenario:
api/user/1
$userId = 1;
$user = getEntityManager()->find('entity\User', $userId);
return $user; // should only load the firstName, lastName, age properties.
api/user/1/posts
$userId = 1;
$user = getEntityManager()->find('entity\User', $userId);
return $user->getPosts(); // should load the firstName, lastName, age properties and the collection of posts.
I already tried 'Extra Lazy Load' functionality that is built-in Doctrine, without any result.
My code:
<?php
/**
* @ORM\Entity
* @ORM\HasLifecycleCallbacks
* @ORM\Table(name = "USER")
*
* @JMS\ExclusionPolicy("all")
* @JMS\AccessorOrder("custom", custom = { "id", "firstName", "lastName" })
*/
class User {
/**
* @ORM\Id
* @ORM\Column(name = "id", type = "integer", options={"unsigned"=true})
* @ORM\GeneratedValue(strategy = "IDENTITY")
* @JMS\SerializedName("id")
* @JMS\Expose
* @JMS\Type("integer")
* @var int
*/
private $id;
/**
* @ORM\Column(name = "firstName", type = "string", length = 255)
* @JMS\SerializedName("firstName")
* @JMS\Expose
* @JMS\Type("string")
* @var string
*/
private $firstName;
/**
* @ORM\Column(name = "lastName", type = "string", length = 255)
* @JMS\SerializedName("lastName")
* @JMS\Expose
* @JMS\Type("string")
* @var string
*/
private $lastName;
/**
* @ORM\OneToMany(targetEntity = "Post", mappedBy = "user", cascade = { "persist" }, fetch="LAZY")
* @JMS\Expose
* @var ArrayCollection<Post>
*/
private $posts;
public function getId() {
return $this->id;
}
public function getFirstName() {
return $this->firstName;
}
public function getLastName() {
return $this->lastName;
public function getPosts() {
return $this->posts->toArray();
}
}
The posts are always loaded after fetching the user object, even though I use fetch type lazy or extra_lazy.