When I wanted to do $this->blah = "blah"; to set the fields to add a new
record in a table using persist/flush, e.g. a new order, I noticed I cannot
set the value for client_id that is a ManyToOne foreign key to Client
entity. I tried to discover how can I do this using the documentation. As
it took 24 hours to figure it out, I post it here for other newbies with
appropriate subject that they can find it by searching the group. First of
all special thanks to Herman who helped me a lot.
An expert please correct me if I am saying something wrong. Are all of
these parts necessary or I've added some unnecessary things?
In Client.php, that is OneToManyClient, we have to have something like this:
public function __construct() {
$this->orders = new ArrayCollection();
}
public function addOrder($order)
{
$this->orders[] = $order;
}
public function setFields($fields)
{
foreach ($fields as $key=>$value) {
$this->$key = $value;
}
}
$metadata->mapOneToMany(array( 'fieldName' => 'orders',
'targetEntity' => 'Entities\\Order',
'mappedBy' => 'client',
'joinColumns' => array( 0 => array( 'name'
=> 'client_id',
'referencedColumnName' => 'client_id',
'nullable' => true,
'columnDefinition' => NULL,
), )
));
==
In Order.php we have this:
public function setClient($client)
{
$client->addOrder($this);
$this->client = $client;
}
public function setFields($fields)
{
foreach ($fields as $key=>$value) {
$this->$key = $value;
}
}
$metadata->mapManyToOne(array( 'fieldName' => 'client',
'targetEntity' => 'Entities\\Client',
'inversedBy' => 'orders',
'joinColumns' => array( 0 => array( 'name'
=> 'client_id',
'referencedColumnName' => 'client_id',
'nullable' => true,
'columnDefinition' => NULL,
), )
));
==
Then to insert $_POST order data to db for client_id = 1, we can do this:
$client = $em->find('Entities\Client', 1);
if ($client === null) {
echo "No client found.\n";
exit(1);
}
$order = new Entities\Order;
$order->setClient($client);
$order->setFields($_POST);
$em->persist($order);
$em->flush();
An expert please correct me if I am saying something wrong. Are all of
these parts necessary or I've added some unnecessary things?
--
You received this message because you are subscribed to the Google Groups
"doctrine-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/doctrine-user.
For more options, visit https://groups.google.com/groups/opt_out.