Totally new to Cake.
I have this table named Content and another one named ContentMeta (related via content_id). Each entry in Content has a corresponding ContentMeta.
When I add new content, this is the code I’m using to add a new entry to ContentMeta:
if( !empty( $this->data ) ) {
// Save Content
$this->Content->create();
$content = $this->Content->save( $this->data );
// Save Meta
if( !empty( $content ) ) {
$this->data['ContentMeta']['content_id'] = $this->Content->id;
$this->Content->ContentMeta->save( $this->data );
$this->Session->setFlash( 'Content has been saved.' );
$this->redirect( array( 'action' => 'edit', $this->Content->id ) );
}
}
This works fine and add one new entry to Content and one to ContentMeta.
When it comes to updating the data (edit mode), I’m running into a slight problem. The entry for Content is getting updated without a hitch, but in the ContentMeta table, a new entry is being created upon every single update.
Here’s the code for updating:
$this->Content->id = $id;
// Update Content
$content = $this->Content->save( $this->data );
// Update Meta
if( !empty( $content ) ) {
//Debugger::dump(print_r($this->data,true));
$this->data['ContentMeta']['content_id'] = $this->Content->id;
$this->Content->ContentMeta->save( $this->data );
$this->Session->setFlash( 'Content has been updated.' );
$this->redirect( array( 'action' => 'edit', $this->Content->id ) );
}
I’m sure it’s some logical error in this block that is causing this to happen. Can anyone give me an idea where I am going wrong?
Thanks,
m^e
For me it’s missing $this->data[‘ContentMeta’][‘id’] in your data array. And because this field is empty the cake attempt to create a new row.
So in your form add a hidden id field for the ContentMeta.
Another thing which I think will improve your code is to use
this way you will save your data at once instead of 2 save() calls for each model. Check the manual in the cookboook (and search for saveAll in the text).