Search code examples
doctrine-ormapi-platform.com

How to retrieve related entities using Doctrine ORM in Symfony?


Title:

I have a product_link table with the following records:

| id_product_link        | product_link_principal          | id_client |
|------------------------|---------------------------------|-----------|
| 1                      | null                            | 9         |
| 2                      | 1                               | 80        |
| 3                      | 1                               | 512       |
| 4                      | null                            | 9         |
| 5                      | 4                               | 80        |
| 6                      | 4                               | 512       |

Currently, I have the following entity mapping in my Symfony application:

class ProductLink
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(name: 'id_product_link')]
    #[Groups(['product_link:read'])]
    private ?int $id_product_link = null;

    #[ORM\ManyToOne(targetEntity: ProductLink::class)]
    #[ORM\JoinColumn(name: 'product_link_principal', referencedColumnName: 'product_link')]
    #[Groups(['product_link:read'])]
    private $relations;

I would like to retrieve the related entities in the following format (I use api-platform)

So I'd like that when I do a get on entity 1 (which has product_link_principal set to null) I want all those who have product_link_principal = 1

{
    "id_product_link": 1,
    "relations": [
        {"id_product_link": 2},
        {"id_product_link": 3}
    ]
}

How can I modify my Doctrine ORM mapping and query to achieve this result?


Solution

  • <?php
    
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(name: 'id_product_link', type: Types::INTEGER)]
    #[Groups(['product_link:read'])]
    private ?int $id_product_link = null;
    
    #[ORM\ManyToOne(targetEntity: ProductLink::class)]
    #[ORM\JoinColumn(name: 'product_link_principal', referencedColumnName: 'id_product_link')]
    #[Groups(['product_link:read'])]
    private ?ProductLink $main;
    
    #[ORM\OneToMany(mappedBy: 'main', targetEntity: ProductLink::class)]
    #[ORM\JoinColumn(name: 'id_product_link', referencedColumnName: 'product_link_principal')]
    #[Groups(['product_link:read'])]
    private Collection $related;
    

    With the corresponding getters I get the following (simplified) result when I GET productLinks/1

    {
        "id_product_link": 1,
        "related": [
            {"id_product_link": 2},
            {"id_product_link": 3}
        ]
    }