I'm trying to import a batch of records (bills) but I have a Many-to-One relationship (with Customer). How do I fill in the DB column for that relationship?
I'm using a fromArray
-like function inside the entity where I pass in the field list and the values for one record (the source of data is a CSV). Then inside that function, I simply assign each of the column values to the corresponding property. However, the property Customer is an object so I would need to pass in an object which I don't have.
I've considered injecting the Entity Manager to my entity but that is regarded as a terrible practice so I'm kind of stuck.
I've also tried adding an extra property customerId
hoping it would force-write the value but it seems to stick to the relationship value over the property value.
Here's my code:
class Bill
/**
* @var string
*
* @ORM\Column(name="docId", type="string", length=25, nullable=false)
* @ORM\Id
*/
private $id;
/**
* @var float|null
*
* @ORM\Column(name="amount", type="float", precision=10, scale=0, nullable=true)
*/
private $amount;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Customer", inversedBy="bills")
* @ORM\JoinColumn(name="customerId", referencedColumnName="customerId", nullable=false)
*/
private $customer;
public function getCustomer(): ?Customer
{
return $this->customer;
}
public function setCustomer( $customer): self
{
$this->customer = $customer;
return $this;
}
//this is where we import
public static function fromCSVRecord($header, $line)
{
$object = new self;
foreach($header as $key => $field){
try{
switch($field){
case 'customerId':
//get the customer here from EM but we don't have EM
$customer = $em->getRepository(Customer::class)->find($line[$key]);
$object->setCustomer($customer);
break;
default:
$object->$field = $line[$key];
break;
}
}catch(\Exception $e){
dd($line[$key]);
}
}
return $object;
}
}
I was hoping there was a simple way to import record values using the ORM without having to inject the Entity Manager into the entity class.