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

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->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?



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



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

Need Your Help

Transform a parse tree of a polynomial to a parse tree of its evaluation according to Horner's scheme

algorithm expression-trees compiler-optimization parse-tree expression-templates

Could you please point me to an algorithm that takes a (binary) parse tree for evaluating a polynomial expression in a single variable and returns an equivalent parse tree that evaluates the polyno...

PHP Setting cookie works on test system, not on live system

php apache cookies

I'm trying to store a cookie after login and it all works fine on a test system but as soon as I put it live it fails? I've tried the standard w3schools code (below) and even this is the same so i...