【发布时间】:2017-03-03 10:54:34
【问题描述】:
我有两张桌子:-
销售
CREATE TABLE `sales` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
`description` text,
`quantity` int(10) DEFAULT NULL,
`price` decimal(18,2) DEFAULT NULL,
`payment_method_id` int(10) DEFAULT NULL,
`user_id` int(10) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
sale_details
CREATE TABLE `sale_details` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`sale_id` int(10) DEFAULT NULL,
`product_id` int(10) DEFAULT NULL,
`quantity` int(10) DEFAULT NULL,
`price` decimal(18,2) DEFAULT NULL,
`total_price` decimal(18,2) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
我需要使用 ajax 将数据相应地插入这些表中。首先,我将数组数据结构化为以下内容。
这是我的数据,
[
'quantity' => 3,
'price' => 63,
'payment_method_id' => 1,
'user_id' => 1,
'sale_details' => [
0 => [
'product_id' => 1,
'quantity' => 2,
'price' => 24,
'total_price' => 48
],
1 => [
'product_id' => 49,
'quantity' => 1,
'price' => 15,
'total_price' => 15
]
]
]
SalesController.php
if ($this->request->is('ajax')) {
$sales = $this->Sales->newEntity(
$this->request->data(),
[
'validate' => 'create',
'associated' => [
'SaleDetails' => ['validate' => 'create']
]
]
);
if ($this->Sales->save($sales)) {
//code
}
}
我设法将数据插入到这些表中,但两个表的主键随着添加数的增加而不断增加 2。我插入了 3 次数据。这是记录数据的方式:-
销售
id title description quantity price payment_method_id user_id created modified
------ ------ ----------- -------- ------ ----------------- ------- ------------------- ---------------------
1 (NULL) (NULL) 3 63.00 1 1 2017-03-03 11:37:11 2017-03-03 11:37:11
sale_details
id sale_id product_id quantity price total_price created modified
------ ------- ---------- -------- ------ ----------- ------------------- ---------------------
1 1 1 2 24.00 48.00 2017-03-03 11:37:11 2017-03-03 11:37:11
2 1 49 1 15.00 15.00 2017-03-03 11:37:11 2017-03-03 11:37:11
您可以从表格中注意到,sales 表格 id 随着 2 的增加而增加,并且 sale_details 表格也发生了这种情况。
我的问题如下:-
1) 我对 cakephp 3 有点陌生,那么这是将数据保存到多个表中的正确方法吗?我删除了以下几行,我仍然能够将数据保存到这些表中。这里的“关联”怎么办?
SalesController.php
if ($this->request->is('ajax')) {
$sales = $this->Sales->newEntity(
$this->request->data(),
[
'validate' => 'create',
/*'associated' => [
'SaleDetails' => ['validate' => 'create']
]*/ // removed
]
);
if ($this->Sales->save($sales)) {
//code
}
}
2) 我不知道为什么这些 id 随着 2 的增加而增加。我很确定我已经为两个表设置了 auto_increment = 1。
系统变量 auto_increment_increment 已设置为 2。但不确定这是怎么发生的。
提前致谢。
【问题讨论】:
标签: cakephp orm save associations cakephp-3.0