[英]CodeIgniter Datamapper save one to many 1:n
我正在使用codeigniter和datamapper來創建一個發票應用程序。
發票has_many Invoice_item
我正在嘗試針對發票保存新的Invoice_items。
如果我做以下事情:
$invoice = new Invoice(1474);
$invoice_item1 = new Invoice_item();
$invoice_item1->description = 'item 1';
$invoice_item2 = new Invoice_item();
$invoice_item2->description = 'item 2';
$items = array($invoice_item1, $invoice_item2);
foreach ($items as $item) {
$item->save($invoice);
}
這很好但我希望我可以做這樣的事情:
$invoice = new Invoice(1474);
$invoice_item1 = new Invoice_item();
$invoice_item1->description = 'item 1';
$invoice_item2 = new Invoice_item();
$invoice_item2->description = 'item 2';
$items = array($invoice_item1, $invoice_item2);
$invoice->save($items);
有可能這樣做嗎? 任何幫助或建議非常感謝,謝謝。
更新:
發票模型
class Invoice extends DataMapper {
public $has_many = array('invoice_item');
public $has_one = array('customer');
public function __construct($id = NULL) {
parent::__construct($id);
}
public function getTotal() {
$this->invoice_item->get_iterated();
$total = 0;
foreach ($this->invoice_item as $item) {
$total += $item->price * $item->qty;
}
return number_format($total, 2);
}
public function getStatus() {
if (!$this->paid) {
$status = date_diff(date_create(date('Y-m-d')), date_create($this->invoice_date))->format('%a') . " days";
} else {
$status = 'PAID';
}
return $status;
}
public function save() {
parent::save();
$this->where('id', $this->id)->update('invoice_no', $this->id);
}
}
Invoice_item模型
class Invoice_item extends DataMapper {
public $has_one = array('invoice');
public function __construct($id = NULL) {
parent::__construct($id);
}
}
如果你使用magick save_{relationname}
函數和數組它應該做你想要的,嘗試:
$invoice->save_invoice_item($items);
如果將數組傳遞給save()
方法,它將嘗試將其中的每個項目解釋為關系,並且要使“* -many”工作,您需要在其中包含第二個數組,因此將發票項目包裝兩次應該執行它也:
$invoice->save(array(array($invoice_item1, $invoice_item2));
不幸的是,當相關對象沒有首先保存到數據庫時,DM似乎沒有處理這種情況(猜測正確的順序不會是微不足道的)。 所以你必須寫它:
$invoice_item1->save();
$invoice_item2->save();
$invoice->save(array(array($invoice_item1, $invoice_item2)));
一旦保存,這將使用發票的ID更新invoice_item行。 這個過程並不理想,因為數據庫保留發票項目沒有相關發票的時刻,建議使用此處的交易。
您可以通過先保存沒有項目的Invoice
而不是使用發票實例保存項目來切換訂單:
$invoice->save();
$invoice_item = new Invoice_item;
// ...
$invoice_item->save($invoice);
您可以通過從$this->db->queries
轉儲查詢來檢查發生了什么。
在您的Invoice
模型中,您將覆蓋原始的save()
方法,但是您不會將參數傳遞給parent::save()
因此這樣的行如下所示:
$invoice->save($invoice_item);
只是忽略參數(php不要抱怨更多參數然后需要)。 你可能想寫這樣的東西:
public function save() {
// passing arguments the way they came,
// it's also more robust against changes in datamapper with func_get_args() + call_user_func()
call_user_func_array(array('parent', 'save'), func_get_args());
$this->where('id', $this->id)->update('invoice_no', $this->id);
}
您的原始示例有效,因為您使用Invoice_item
類的save()
方法進行save()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.