Use two fields in a Manytoone relation

Asked

Viewed 66 times

0

There is the following relationship between two entities:

class Clients
{
    //...

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

     //...
}

Note that there is a relationship with the entity Dealerships across the field dealership_id.

In the entity Dealerships 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 property exists active.

If there is a record with ID 1 in the table Dealerships, in the object clients just 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 relationship if the field active is equal to 1.

You can do this using Doctrine?

1 answer

0


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

First we look for Democracy:

$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 Statement is not null, simply 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 singular, since they usually handle a single object; also, avoid manipulating id’s in the relations between objects).

  • Rodrigo, I did not understand your statement not to use ids in the relations between objects. How so?

  • What I meant is that normally in the relations between objects you can omit the id’s, the Doctrine is intelligent enough to know how the relationship between one object and another takes place. Prefer to use methods such as setDealership and setClient.

  • Thank you so much for your help. I use the object instead of the ID, but to simplify the example I put the ID right away. Thanks for the help.

Browser other questions tagged

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