Reputation: 9990
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.
Upvotes: 0
Views: 62
Reputation: 1359
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
Upvotes: 1