简体   繁体   中英

Symfony2 and Doctrine - ManyToOne

I am trying to understand Symfony2, but there is something that is not making sense to me. I reversed engineered an existing database to produce my entities, so maybe thats the problem.

I have a table called availability_alert, nothing special, a few fields including an id (which is the primary key). This table has no link to anything else.

I then have a second table called booking_class, once again nothing special, but it does have the field $availabilityAlert which links to the availability_alerts tables id.

In essence, an Availability Alert can have one or many Booking Class.

Now in my booking class entity, I have the link

/**
 * @var \AlertBundle\Entity\AvailabilityAlert
 *
 * @ORM\ManyToOne(targetEntity="AlertBundle\Entity\AvailabilityAlert")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="availability_alert_id", referencedColumnName="id")
 * })
 */
private $availabilityAlert;

So this all looks ok. The setter for it though came out like so

public function setAvailabilityAlert(\AlertBundle\Entity\AvailabilityAlert $availabilityAlert = null)
{
    $this->availabilityAlert = $availabilityAlert;

    return $this;
}

So that appears to take an AvailabilityAlert Object as a parameter, not the AvailabilityAlert id?

So with the above, I am presuming doing something like this in my controller will not work?

$alert = new AvailabilityAlert();

$bookingClass = new BookingClass();
$bookingClass->setAvailabilityAlert($alert->getId());

Could someone give me some advice on whether things are correct here, or if I should be doing something else? Essentially AvailabilityAlert should be a static table, other tables link to this.

Any advice appreciated.

Thanks

Yes this is correct.

In the Doctrine world, you are working with objects, not with integers or strings, when it comes to relationships between Entities.

You can read more about Doctrine 2 relationships here: http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations

That's correct. You don't use integers, strings. It's because the relationships are given in entity annotations and Doctrine uses them to figure out what is used exactly to reference the one object from the other. This even let you change how objects reference themselves - for example you change the id to a compound primary key in AvailabilityAlert class and your code wouldn't change much except for the annotations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM