HTTP Post应该如何保存模型和关联模型数据? [英] How should HTTP Post look like for saving model and associated model data?

查看:252
本文介绍了HTTP Post应该如何保存模型和关联模型数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Cakephp 2.4.5。我有两个表与一对多的关系。表B属于表A。

I am using Cakephp 2.4.5. I have 2 tables with a one-to-many relationship. Table B belongs to Table A.

我想要一个表A中的控制器,它可以保存表A和表B中的记录。控制器代码应该很简单,看起来像这样;

I want a controller in Table A that can save records in Table A and Table B. The controller code should be simple and looks like this;

public function add_tableA($id=null)
{
    if ($this->request->is('post')) 
    {
        $this->layout = null ;
        $this->TableA->create();                
        $this->TableA->saveAll($this->request->data, array('deep' => true));
    }
}

我的问题出现在尝试发送正确的HTTP POST格式到控制器。

My problem comes when trying to send the right HTTP POST format to the controller.

我尝试HTTP POST下面的数据格式,但它失败。

I tried to HTTP POST the data format below but it fails.

data[TableA][field1] = field1_value
data[TableA][field2] = field2_value
data[TableB][field1] = field1_value
data[TableB][field2] = field2_value

然后,我尝试HTTP POST下面的数据格式,

Then, I try to HTTP POST the data format below, at least TableA fields are populated.

data[TableA][field1] = field1_value
data[TableA][field2] = field2_value

如果我想为两个表创建行,HTTP POST数据格式应该如何?

How should the HTTP POST data format look like if I want to create rows for both tables?

推荐答案

请参阅: http://book.cakephp.org/2.0/en/models/saving-your-data.html

和saveAssociated的示例:

and example for saveAssociated:

$data = array(
    'Article' => array('title' => 'My first article'),
    'Comment' => array(
        array('body' => 'Comment 1', 'user_id' => 1),
        array('body' => 'Comment 2', 'user_id' => 12),
        array('body' => 'Comment 3', 'user_id' => 40),
    ),
);

因此,在您的案例中发布

So, in your case post something like

data[TableA][field1] = field1_value
data[TableA][field2] = field2_value
data[TableB][0][field1] = field1_value
data[TableB][0][field2] = field2_value
data[TableB][1][field1] = field1_value
data[TableB][1][field2] = field2_value
etc

和:

$this->TableA->saveAssociated($this->request->data);

这篇关于HTTP Post应该如何保存模型和关联模型数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆