I get xml data from external soap server, parsing data and create Object. Next I want to persist it in database but it does't work.
Company id, I get from external soap and its string unique value like 387sdfh899ohkadkfh8
.
Company
/**
* @ORM\Entity
*/
class Company
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="NONE")
* @ORM\Column(type="string")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Address", mappedBy="company", orphanRemoval=true, cascade={"persist","remove"})
*/
private $addresses;
// ...
}
Address
/**
* @ORM\Entity
*/
class Address
{
// ...
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Company",inversedBy="adresses")
* @ORM\JoinColumn(nullable=false)
*/
private $company;
// ...
}
CompanyController
class CompanyController
{
// ...
$json = $serializer->serialize($data, 'json');
$obj = $serializer->deserialize($json, 'array<App\Entity\Company>', 'json');
// ...
}
Every thing looks as expected. Object was created including two Address objects.
This is structure what I get from deserialize
array:1 [
0 => Company {#524
-id: "0946346d06ffe3f551a80700c2a5c534"
// ..
-addresses: ArrayCollection {#538
-elements: array:2 [
0 => Address {#1017
-id: null
// ...
-company: null
}
1 => Address {#537
-id: null
// ..
-company: null
}
]
}
-status: "Active"
}
]
But when I try to store it in database:
CompanyController
class CompanyController
{
// ...
$em= $this->getDoctrine()->getManager();
foreach ($obj as $o) $em->persist($o);
$em->flush();
// ...
}
I'm getting error
inserting address doesn't include id of company. company_id is setting to
null
Similar json data, including addresses corresponding to company I'll be getting from client with json format, parsing it via FormType and store to database but I can't manage with :/
How should I insert that related objects in proper way?
Ok, I solved the problem
Company
/**
* @ORM\OneToMany(targetEntity="App\Entity\Address", mappedBy="company", orphanRemoval=true, cascade={"persist","remove"})
* @JMS\Accessor(setter="setAddresses")
*/
private $addresses;
And added method:
/**
* @param ArrayCollection $addresses
* @return Company
*/
public function setAddresses(ArrayCollection $addresses): self
{
if ( !$this->addresses instanceof ArrayCollection ){
$this->addresses = new ArrayCollection();
};
foreach ($addresses as $address){
if (!$this->addresses->contains($address)) {
$this->addresses[] = $address;
$address->setCompany($this);
}
}
return $this;
}
I spend on this issue two days :/ and solution was so easy, @malarzm Thanks for suggestion it helped me a lot.
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.