Using Two Fields in a ManyToOne Relationship

0

The following relationship exists between two entities:

class Clients
{
    //...

    /**
     * Dealership id
     * 
     * @ManyToOne(targetEntity="Dealerships", inversedBy="clients", fetch="EXTRA_LAZY")
     * @JoinColumn(name="dealership_id", referencedColumnName="id")
     */
     private $dealershipId;

     //...
}

Notice that there is a relationship with the Dealerships entity through the dealership_id field.

In the Dealerships ed entity I have the following structure:

class Dealerships
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
     private $id;

     /**
     * @var int
     *
     * @ORM\Column(name="active", type="integer")
     */
     private $active;

     //...
}

Notice that the active property exists.

If there is a record with ID 1 in the Dealerships table, in the clients object simply do the following:

$client = new Clients();
$client->setDealershipId(1);

The code above works because there is ID 1, but in the relation I want to consider 1 more field, the active , that is, only accept the relation if the field active is equal to 1.

Is it possible to do this using Doctrine?

    
asked by anonymous 23.06.2016 / 16:54

1 answer

0

I think it is easiest to find the object of type Dealerships by EntityManager and, if it is not null, assign it to the object of type Clients .

First we look for the dealership:

$dealership = $this
    ->getDoctrine()
    ->getEntityManager()
    ->createQuery('
        SELECT d
        FROM Dealerships d
        WHERE id = :id
        AND active = :active')
    ->setParameter('id', $id)
    ->setParameter('active', true)
    ->getOneOrNullResult();

If this dealership is not null, just assign it to the customer:

if ($dealership instanceof Dealerships) {
    $client = new Clients();
    $client->setDealershipId($dealership->getId());
}

(ps: the names of the classes of your models should be in the singular, since they usually manipulate a single object, and avoid manipulating id's in relations between objects).

    
23.06.2016 / 18:26