当所有者对象调用它们时,我一直在尝试获取关联的行来执行beforeSave函数。在本例中,我使用Asset和AssetVersion作为Asset hasMany Versions。
我的目的是在AssetVersion模型中使用beforeSave,通过find查找最新的当前版本号,然后将其放入DB中。我当然不能在控制器中使用saveAssociated并捕获asset_id然后在AssetVersion模型上调用save但是感觉不是正确的方法。 beforeSave在Asset中调用,但不在AssetVersion中调用。
class AssetsController extends AppController
{
public function add()
{
if (!$this->request->is('post'))
return false;
$md5 = md5(microtime(true));
$data['Versions'] = array(
array(
'md5' => $md5,
)
);
debug($data);
$this->Asset->create();
if ($this->Asset->saveAll($data))
{
die('boom');
$this->Session->setFlash(__('The asset has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The asset could not be saved. Please, try again.'));
}
}
}
class Asset extends AppModel
{
public $hasMany = array(
'Versions' => array(
'className' => 'AssetVersions'
)
);
public function beforeSave($options = array())
{
if(!isset($this->data['Asset']['created_id']))
$this->data['Asset']['created_id'] = CakeSession::read('Auth.User.id');
$this->data['Asset']['updated_by'] = CakeSession::read('Auth.User.id');
return parent::beforeSave();
}
}
class AssetVersion extends AppModel
{
public $belongsTo = array(
'Asset'
);
public function beforeSave($options = array())
{
debug('I dont get called at all');
debug($this->data);
die();
}
}
知道我做得不对吗?我一直在尝试调试在CakePHP本身调用的内容,并且到目前为止证明了在保存相关数据时调度事件但我根本没有在AssetVersion中看到我的调试。