How should HTTP Post look like for saving model and associated model data?

雨燕双飞 提交于 2020-01-17 00:30:46

问题


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

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));
    }
}

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

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

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

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


回答1:


See: http://book.cakephp.org/2.0/en/models/saving-your-data.html

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

and:

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



回答2:


In order to save it like that you need to have:

data[TableB][TableA_id] = 'id of data saved be to TableA';

for TableB data to be saved. So I think you need to first save TableA:

$dataA = $this->TableA->save('data for TableA');
if (!$dataA) {
   $data['TableB']['TableA_id'] = $this->TableA->id;
   $this->TableA->TableB->save('data array for TableB');
}


来源:https://stackoverflow.com/questions/22346721/how-should-http-post-look-like-for-saving-model-and-associated-model-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!