0
votes

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?

2
How does your form look like?skywalker
I am not using a HTML form. Not using cakephp views. I am going to use Cakephp purely as a REST API server. I am using python to directly send a HTTP Post. This is why I need to know the data format to be sent in the HTTP Post.user781486
I think, you should use saveAssociated() instead of saveAll(). Check the data structure at its official site.Vikash Pathak
@ Vikash Pathak: I tried saveAssociated() but it still does not work.user781486
For example, TableB belongsTo TableA, I think in this case you can't save from TableA, did you try to save from TableB? You have to add relation to tableA where TableA hasMany TableB. Do you have that in your model?skywalker

2 Answers

2
votes

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);
1
votes

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