简体   繁体   中英

Persisting related entities in Symfony correctly (Foreign Keys)

I have two objects: Company and Location

A company can have many locations (say to represent each city they have an office in).

I've set up the models/entities to represent this relationship:

Location: id, address, company
Company: id, name, locations

So I have the auto-generated function on Company:

public function addLocation(Location $locations)
{
    $this->locations[] = $locations;
    return $this;
}

My question is, if I want to add both a new company and new locations to my database - can I do it simply by adding to the locations in Company? Will Symfony be smart enough to figure out all the foreign key IDs?

Say I want to create:

$company = new Company();
$company->setName('NEW COMPANY');

$location1 = new Location();
$location1.setAddress('123 Fake St');
// $location1.setCompany($company) // Is this required?

$location2 = new Location();
$location2.setAddress('456 Test Hwy');
// $location2.setCompany($company) // Is this required?

$company->addLocation($location1);
$company->addLocation($location2);

I'm curious how this works, or if I'm barking up the wrong tree and should just add the companies in one transaction and then add the locations later. Any thoughts appreciated - thanks.

You can do it like that:

<?php

/** @Entity */
class Company
{
    // ...

    /**
     * @ManyToMany(targetEntity="Location", inversedBy="companies")
     * @JoinTable(name="company_location")
     */
    private $locations;

    public function __construct() {
        $this->locations = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity */
class Location
{
    // ...
    /**
     * @ManyToMany(targetEntity="Company", mappedBy="locations")
     */
    private $companies;

    public function __construct() {
        $this->companies = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

I think you're looking for cascade persisting, read more here: Doctrine 2 ManyToMany cascade

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