I have a package with two custom db tables, Invoice and Donation. An Invoice contains one or more Donations, and the invoice_id is the key between the two. Here’s the schema file:
<?xml version="1.0" encoding="UTF-8"?>
<model package="mscd" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM">
<object class="Donation" table="donation" extends="xPDOSimpleObject">
<field key="invoice_id" dbtype="int" precision="11" phptype="integer" null="false" />
<field key="category" dbtype="varchar" precision="16" phptype="string" null="false" />
<field key="category_item_id" dbtype="int" precision="11" phptype="integer" null="false" />
<field key="donation_amount" dbtype="decimal" precision="10,0" phptype="float" null="false" />
<index alias="PRIMARY" name="PRIMARY" primary="true" unique="true">
<column key="id" collation="A" null="false" />
</index>
<aggregate alias="Invoice" class="Invoice" local="invoice_id" foreign="invoice_id" cardinality="one" owner="foreign" />
</object>
<object class="Invoice" table="invoice" extends="xPDOObject">
<field key="invoice_id" dbtype="int" precision="11" phptype="integer" null="false" index="pk" generated="native" />
<field key="invoice_time" dbtype="timestamp" phptype="timestamp" null="false" default="CURRENT_TIMESTAMP" />
<field key="donor_email" dbtype="varchar" precision="128" phptype="string" null="false" />
<field key="donation_total" dbtype="decimal" precision="10,0" phptype="float" null="false" />
<field key="donation_recieved" dbtype="tinyint" precision="1" phptype="integer" null="false" default="0" />
<index alias="PRIMARY" name="PRIMARY" primary="true" unique="true">
<column key="invoice_id" collation="A" null="false" />
</index>
<composite alias="Donations" class="Donation" local="invoice_id" foreign="invoice_id" cardinality="many" owner="local" />
</object>
</model>?
When a form is submitted, I am trying to generate a new Invoice and then a new (related) Donation for each donation item that was submitted with the form. The script looks like this:
$modx->addPackage('mscd',MODX_CORE_PATH.'components/mscd/model/','');
$Inv = $modx->newObject('Invoice');
$Inv->set('donor_email', $_POST['email1']);
$Inv->set('donation_total', $_POST['donations_total_amount']);
foreach($_POST as $k=>$v) {
if (strpos($k,'donation_') !== FALSE) {
// this parses some fields out of the input name
$flds = explode('_',$k);
$type = $flds[1];
$dID = $flds[2];
$dNm = $flds[3];
$Don = $modx->newObject('Donation');
$Don->set('category', $dID);
$Don->set('category_item_id', $dNm);
$Don->set('donation_amount', $v);
$Don->save();
$add = ($Inv->addOne($Don)) ? 'added a Donation to the Invoice' : 'failed to add Donation to Invoice';
$info .= $add . print_r($modx->errorInfo(),true);
}
}
$Inv->save();
My Invoice and my individual Donations are being written to the database table, but the relationship is not working. The ’invoice_id’ value for the Donations is being set to zero.
What am I doing wrong?