I need some expert to advice that how to save a record, for example a Invoice table record, which has many Item records.
My problem is, I need to save the Invoice, and also need to save all the Items which has the newly auto generated invoice id by MySQL, I can do the following:
$newInvoice->save();
foreach($items as $item) {
$item->invoiceId = $newInvoice->id;
$item->save();
}
You mean before I can add a beforeValidate in this Invoice ActiveRecord class, inside this function beforeValidate() I can check every items validation, in the case of not valid, then return false. As the result, the code $newInvoice->save() will return false, which is what I want exactly, (correct? is this the way?)
class Invoice extends CActiveRecord
{
..
..
public function afterSave() {
# Save each items, do not validate here course already done inside beforeValidate()
foreach($this->items as $item) { /* @var $item Item */
$item->itemId = $this->id; # $this is Invoice
$item->save();
}
return parent::afterSave();
}
...
public function beforeValidate() {
# Do validate all items here, return false if one of the items cannot validated.
}
...
}
Please correct me if I miss understand. Thanks for your advice.