如何将数据库行从一个表复制到cakephp中的另一个表

时间:2012-04-18 08:16:15

标签: cakephp cakephp-1.3

我想将一行数据从一个表复制到另一个表。我要复制的表有id,name,password字段。应该复制值的表具有id,name,password,post_count字段。

我正在尝试使用以下代码,但它没有帮助。

$data=$this->Register->find(null, $id);
if($this->User->save($data)) {
    $this->Session->setFlash(__('Data copied'), true);
}

我该怎么办?

我已经删除了要将值复制到的表格的验证。

提前致谢

3 个答案:

答案 0 :(得分:1)

查询$this->Register->find(null, $id);以某种不同的格式返回数据。相反,我改变了查询。代码在

之下
$condition = array('id'=>$id);
$data=$this->Register->find('first', array('conditions'=>$condition));
$newdata = array(
            'User' => array(
                'name' => $data['Register']['name'],
                'password' => $data['Register']['password']
       )
);
if($this->User->save($newdata)) {
      $this->Session->setFlash(__('Data copied'), true);
}

这有效,因为find('first')的返回返回一个数组,可以根据我们的需要进行修改,然后我们可以调用User模型的save方法。

答案 1 :(得分:0)

$data = array();
$data = $this->Register->read(null, $id);

$newdata = array();
$newdata = array(
          'User' => array(
                      'name' => $data['Register']['name'],
                      'password' => $data['Register']['password']
                   )
        );
// If you are in Register controller then import User model 

if($this->User->save($newdata, false)) {
    $this->Session->setFlash(__('Data copied'), true);
}

答案 2 :(得分:0)

我认为这不适合你的原因是因为该ID的注册记录不存在。在尝试保存之前,您必须检查结果是否包含数据。这就是你在INSERT语句中得到NULL,NULL的原因。

$record = $this->Register->findById($id);
if(!empty($record))
{
   $this->User->create();
   if($this->User->save(array('User'=>$record['Register']),false,array('name','password')))
   {
      $this->Session->setFlash(__('Data copied'), true);
   }
}
else
{
   $this->Session->setFlash(__('Data not found'), true);
}
相关问题