Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何将自动递增主键附加到同一表中的另一个字段?_Mysql_Yii_Auto Increment - Fatal编程技术网

Mysql 如何将自动递增主键附加到同一表中的另一个字段?

Mysql 如何将自动递增主键附加到同一表中的另一个字段?,mysql,yii,auto-increment,Mysql,Yii,Auto Increment,我正在使用yii active records for mysql,我有一个表,其中有一个字段需要附加同一个表的主键。主键是一个自动递增字段,因此在保存之前我无法访问主键。 $model->append_field = "xyz".$model->id; // nothing is appending $model->save(); $model->append_field = "xyz".$model->id; //id is now available 我该怎

我正在使用yii active records for mysql,我有一个表,其中有一个字段需要附加同一个表的主键。主键是一个自动递增字段,因此在保存之前我无法访问主键。

$model->append_field = "xyz".$model->id; // nothing is appending
$model->save();
$model->append_field = "xyz".$model->id; //id is now available
我该怎么做?

我知道我可以在插入后立即更新,但是有更好的方法吗?

只有在执行INSERT语句后,才会为您的记录分配一个
id
。无法确定插入之前的
id
是什么,因此您必须在插入之后使用连接的字段值执行更新

您可以在MySQL中编写一个存储过程或触发器来为您执行此操作,因此您的应用程序执行一条SQL语句来完成此操作。但是,您只是将逻辑移到MySQL中,最终插入和更新都会发生。

还有一些解决方法:

这几乎就是你的方法;)

但是您可以使用自定义的afterSave()方法将此功能移动到行为中,请注意,您必须注意不要循环事件

或者只是为它写一个getter

function getFull_append_field(){
  return $this->append_field.$this->id;  
}

但是,您不能在SQL语句中使用它,除非您使用CONCAT()或类似的方法在那里创建属性。

其他人可能会对我是如何实现它感兴趣,下面是代码:

//in the model class
 class SomeModel extends CActiveRecord{
  ...
  protected function afterSave(){
     parent::afterSave();
     if($this->getIsNewRecord()){
        $this->append_field=$this->append_field.$this->id;
        $this->updateByPk($this->id, array('append_field'=>$this->append_field));
     }
  }
 }
避免事件循环的一种方法(如@schmunk所述)是在
afterSave()
方法中使用
saveAttributes(…)
,但saveAttributes(…)检查isNewRecord,并仅在它是新记录时插入值,因此要求我们使用
setNewRecord(false)

我发现saveAttributes(…)实际上调用了
updateByPk(…)
,所以我直接使用了updateByPk(…)本身。

+1谢谢,我以前做过
$model->save()
,现在我使用的是afterSave()。此外,我看到的所有concat()示例都只在select中使用它,而不是在insert中使用它,因此我将进行两个sql调用。
//in the model class
 class SomeModel extends CActiveRecord{
  ...
  protected function afterSave(){
     parent::afterSave();
     if($this->getIsNewRecord()){
        $this->append_field=$this->append_field.$this->id;
        $this->updateByPk($this->id, array('append_field'=>$this->append_field));
     }
  }
 }