Cakephp 3 存储关联数据
Cakephp 3 store associated data
我从 cakephp2 切换到 cakephp3。在这里我无法理解如何存储关联数据。我有一个名为 Orders 的 table 和一个名为 Ordersarticles 的 table。有一个视图,其中放置了订单信息和多个orderarticles。现在我想将数据存储在控制器中。
我有以下代码
public function add(){
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$i = 0; //Index for each Field
foreach($order->Orderarticles['article_id'] as $oaarticleid){
$orderarticles = [
'article_id' => $oaarticleid,
'amount' => $order->Orderarticles['amount'][$i]
];
$i++;
}
$order['Orderarticles'] = $orderarticles;
//Store Order
if ($result = $this->Orders->save($order)) {
//Store orderArticles
$this->Flash->success(__('The order has been saved.'));
//return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The order could not be saved. Please, try again.'));
}
循环中的 orderArticles 是为正确的格式准备的。但是,当我想存储信息时,只存储订单,而不存储订单。我完全不知道如何存储附加信息...
我也尝试过先存储订单,获取插入的 ID,然后存储订单商品。但我完全失败了。我觉得在 Cakephp 中是新的。你能帮帮我吗?
我猜你在保存订单后不想做这样的事情。
if ($result = $this->Orders->save($order)) {
$articles = $this->request->getData("articles");
$i = 0;
foreach ($articles as $article) {
$data = [
'article_id' => $result->id,
'amount' => $i++
];
$article = $this->Orderarticles->newEntity();
$article = $this->Orderarticles->patchEntity($article, $data);
$this->Orderarticles->save($article);
}
}
我从 cakephp2 切换到 cakephp3。在这里我无法理解如何存储关联数据。我有一个名为 Orders 的 table 和一个名为 Ordersarticles 的 table。有一个视图,其中放置了订单信息和多个orderarticles。现在我想将数据存储在控制器中。
我有以下代码
public function add(){
$order = $this->Orders->newEntity();
if ($this->request->is('post')) {
$order = $this->Orders->patchEntity($order, $this->request->getData());
$i = 0; //Index for each Field
foreach($order->Orderarticles['article_id'] as $oaarticleid){
$orderarticles = [
'article_id' => $oaarticleid,
'amount' => $order->Orderarticles['amount'][$i]
];
$i++;
}
$order['Orderarticles'] = $orderarticles;
//Store Order
if ($result = $this->Orders->save($order)) {
//Store orderArticles
$this->Flash->success(__('The order has been saved.'));
//return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The order could not be saved. Please, try again.'));
}
循环中的 orderArticles 是为正确的格式准备的。但是,当我想存储信息时,只存储订单,而不存储订单。我完全不知道如何存储附加信息...
我也尝试过先存储订单,获取插入的 ID,然后存储订单商品。但我完全失败了。我觉得在 Cakephp 中是新的。你能帮帮我吗?
我猜你在保存订单后不想做这样的事情。
if ($result = $this->Orders->save($order)) {
$articles = $this->request->getData("articles");
$i = 0;
foreach ($articles as $article) {
$data = [
'article_id' => $result->id,
'amount' => $i++
];
$article = $this->Orderarticles->newEntity();
$article = $this->Orderarticles->patchEntity($article, $data);
$this->Orderarticles->save($article);
}
}