保存belongsTo模型

问题描述:

我有2个型号:照片得分。每个Photo,应该有一个Score。所以我设置Photo属于Score保存belongsTo模型

class Photo extends AppModel { 
    public $actsAs = array('Containable'); 
    public $belongsTo = array('Score'); 
} 

scores表有一个photo_id列。 (对于其photo ID)

但是,有一个问题....如何保存photoscore

正如你问你的问题:“每个Photo,应该有一个Score”。所以你必须改变你的照片模型。这看起来像:

class Photo extends AppModel { 
     public $actsAs = array('Containable'); 
     public $hasOne = array('Score'); 
} 

您将不得不使用该模型来调用saveAll()方法,该方法需要先保存。因此,其他关联模型可能会将新插入记录的值视为外键。

$this->Photo->saveAll($this->request->data, array('deep' => true)); 

您的要求阵列($this->request->data)应该是这样的:

Array(
    [Photo] => Array(
         [img_name] = abc.jpg 
         [image_group] = cricket 
           ... other fields ... 
        ) 
    [Score] => Array(
         [score_gain] => 10 
            ... other fields .... 
        ) 
    ) 

This link会帮助你。如何保存相关数据。您也可以使用saveAssociated()方法。

我希望它能为你工作。