Search code examples
phpsymfonydoctrine-ormone-to-manysymfony6

Symfony $this->getUser() without doctrine associations (OneToMany)


In Symfony, we can get current logged-in user data using $this->getUser(), but my problem is when I access this statement, I am getting all the user-associated data set. which has OneToMany relationships with another entity, and it has a lot of data.

Example:

User Entity

`

class User implements UserInterface
{
    /**
     * @var string
     * @ORM\Id
     * @ORM\Column(type="string", length=10)
     *
     */
    protected $id;

    /**
     * @var string
     * @ORM\Column(type="string")
     */
    protected $email;


    /**
     * @var array
     * @ORM\Column(type="json")
     */
    protected $roles;


    /**
     * One User has Many Posts.
     * @ORM\OneToMany(targetEntity="App\Entity\Post", mappedBy="user", fetch="LAZY")
     *
     *
     */
    private Collection  $posts;

`

Post Entity

`

class Post
{
    /**
    * @var string
    * @ORM\Id
    * @ORM\GeneratedValue(strategy="AUTO")
    * @ORM\Column(type="integer", length=11)
    */
    private $id;

  

    /**
    * Many posts have one user.
    * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="post", fetch="EXTRA_LAZY")
    * @ORM\JoinColumn(name="userId", referencedColumnName="id")
    */
    private $user;

`

I am looking to get rid of the user-associated data set or limit the associated data set to limit 1.

Thank you for the help in advance. :)


Solution

  • found solution after hours of search.

    You will be required to add Symfony Serializer #Ignore attribute on the Entity class.

    Example

    use Symfony\Component\Serializer\Annotation\Ignore;
    
    class User implements UserInterface
    {
        /**
         * @var string
         *
         */
        #[ORM\Id]
        #[ORM\Column(type: 'string', length: 10)]
        protected $id;
    
        /**
         * @var string
         */
        #[ORM\Column(type: 'string')]
        protected $email;
    
    
        /**
         * @var array
         */
        #[ORM\Column(type: 'json')]
        protected $roles;
    
    
        /**
         * @var Post
         */
        #[ORM\OneToMany(targetEntity: 'App\Entity\Post', mappedBy: 'user', fetch: 'LAZY')]
        #[Ignore]
        private Collection  $posts;
    

    I hope this help someone. Cheers!