问题
I've got an existing Showcase that hasOne
Gallery.
The Gallery already exists with the foreignKey showcase_id
set to the proper value.
The Gallery has a text field that I try to update via the Showcase-controller.
The result I get is an extra Gallery entry, along the original one, instead of an update of the original entry.
What am I doing wrong?
My Showcase-view looks as follows:
echo $form->create('Showcase', array('action'=>'update'));
echo $form->input('Showcase.id', array('type'=>'hidden', 'value'=>$showcase['Showcase']['id']));
echo $form->input('Gallery.fulltext', array('type'=>'textarea', 'between'=>'<br>', 'value'=>$showcase['Gallery']['fulltext']));
echo $form->submit('Submit text');
echo $form->end();
My Showcase-controller function:
$uses = array('Showcase','Gallery')
function update(){
if(!empty($this->data)){
$this->Showcase->saveAll($this->data, array('validate'=>'first'));
}
}
The Showcase model $hasOne = 'Gallery'
and the Gallery model $belongsTo = 'Showcase'
.
Is $this->Showcase->saveAll()
the proper function to use here? Or do I maybe need to update the Gallery entry within the Gallery controller? That will probably work but is seems so un-elegant.
回答1:
I can see what you mean by being un-elegant, it would be nice if it realised you had a hasOne relationship and therefore updated any existing record.
However currently within the framework I think your best option would be to add echo $form->input('Gallery.id', array('type'=>'hidden', 'value'=>$showcase['Gallery']['id']));
to your view.
As a side note. In the controller action that is currently defining $showcase
if you instead assign it to $this->data
then you won't need to always specify 'value' => ...
in your form inputs.
来源:https://stackoverflow.com/questions/2037352/update-hasone-relation-behaves-strangely-cakephp