我正在开发一个发票系统,我正在尝试以单一形式添加发票。现在我只能添加到我的 invoices 表,而不是 invoices_works 表。这是我正在使用的。提前抱歉添加了这么多代码:
我的发票表:
CREATE TABLE `invoices` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`commission` double NOT NULL DEFAULT '30',
`location_id` int(11) unsigned NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `location_id` (`location_id`),
CONSTRAINT `invoices_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `locations` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
我的 invoices_works 表:
CREATE TABLE `invoices_works` (
`invoice_id` int(11) unsigned NOT NULL,
`work_id` int(11) unsigned NOT NULL,
`count` int(11) NOT NULL DEFAULT '1',
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
KEY `invoice_id` (`invoice_id`),
KEY `work_id` (`work_id`),
CONSTRAINT `invoices_works_ibfk_2` FOREIGN KEY (`work_id`) REFERENCES `works` (`id`),
CONSTRAINT `invoices_works_ibfk_1` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=latin1;
我的作品表:
CREATE TABLE `works` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`cost` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
我的发票模型(至少是 HABTM):
public $hasAndBelongsToMany = array(
'Work' => array(
'className' => 'Work',
'joinTable' => 'invoices_works',
'foreignKey' => 'invoice_id',
'associationForeignKey' => 'work_id'
)
);
在Controller中添加的方法:
public function add() {
if($this->request->is('post')) {
$this->Invoice->create();
if ($this->Invoice->saveAssociated($this->request->data)) {
$this->Session->setFlash(_('The invoice has been saved.'), true);
echo var_dump($this->data);
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(_('The invoice could not be saved.', true));
}
}
$work = $this->Work->find('list');
$location = $this->Location->find('list', array('conditions' => array('Location.id !=' => 0)));
$this->set('works', $work);
$this->set('locations', $location);
}
最后,视图本身:
<?php
echo $this->Form->create('Invoice');
echo "<fieldset>";
echo $this->Form->input('location_id');
echo $this->Form->input('commission', array('default' => 30));
echo "</fieldset>";
//echo $this->Form->hidden('InvoiceWork.invoices_id', array('default' => 1));
echo "<fieldset>";
echo $this->Form->input('InvoicesWork.work_id');
echo $this->Form->input('InvoicesWork.count', array('default' => 1));
echo "</fieldset>";
echo $this->Form->end('Save Invoice');
?>
好像我错过了什么,我知道一旦我找到它就会很明显。