Relationship in the Doctrine

Asked

Viewed 473 times

0

I have a problem that is analogous to the following situation:

A car may or may not have a driver, or a car may have at least 0 and at most 1 driver.

A driver may or may not have a car, ie a driver may have at least 0 and at most 1 car.

In the example in question we are accepting that the driver may have in the max a car.

Turning this into a class we would then have two classes.

<?php 
class Carro{
    /**
    * esse deve aceitar null
    */
    private $motorista;
}


class Motorista{
    /**
    * esse deve aceitar null
    */
    private $carro;
}

In my view the mapping that would interest me most would be Onetoone, but I don’t know if it should be Onetomany or Manytoone, if it were possible to get him to accept null values, however, I would like to know what is the best way to do using Doctrine and the most correct form according to Designer Partner (I wonder because it may be that the best way to do using Doctrine is not the most correct way).

1 answer

1


For me, the class Carro would have an attribute $motorista, as well as the class Motorista would have the attribute $carro (resulting in a one-to-one, bidirectional relationship). Both attributes would be nullable.

So you would have a Car table and a Driver table, and the Driver table has a column referencing Car.

Note that this restriction would only be at the level of your application - if someone wanted to enter the data directly into the database, going over the restriction, they could.

<?php

/**
 * @ORM\Entity
 */
class Carro
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @OneToOne(targetEntity="Motorista", mappedBy="carro")
     * @JoinColumn(nullable=true)
     */
    private $motorista;
}

/**
 * @ORM\Entity
 */
class Motorista
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @OneToOne(targetEntity="Carro", inversedBy="motorista")
     * @JoinColumn(nullable=true)
     */
    private $carro;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.