'Trouble with Api Symfony relation OnetoOne
I created a back API with Symfony and a front with React. To communicate between back and front I'm using API PLATFORM.
I created in Symfony one entity "users" and one entity "customers" with a relation OneToOne. In React when I create a new Customer I automatically create a new User for the same person. This works perfectly.
In my table Customer a column "user_id" has been automatically created by the relation. In this column I find the id of user which corresponds to the customer.
Via react I need to do a request with API Platform in direction of the Entity User to find the id of the customer which corresponds to the User. I don't have a column client_id because I made the relation OneToOne in the client entity.
I can't find the solution.
Solution 1:[1]
You have to complete your entity, by default a OneToOne relation is not bidirectionnal, adding cascade persist and above all JoinColumn on the two sides:
class Customer
{
/**
* @ORM\OneToOne(targetEntity=User::class, inversedBy="customer", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="SET NULL")
*/
private $user;
// getters / setters
}
class User
{
/**
* @ORM\OneToOne(targetEntity=Customer::class, mappedBy="customer", cascade={"persist", "remove"})
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id", onDelete="SET NULL"))
*/
private $customer;
// getters / setters
}
then launch the command to create the migration:
php bin/console d:m:diff
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MILLION Alexandre |
