使用一个模型cakephp 3将数据保存到多个数据库表

时间:2019-01-10 10:14:39

标签: cakephp orm cakephp-3.0

我有两个具有相同表的数据库。

db1.wafer_types表:-

ID    waferType   name
1071  req_1       req_1_name
1072  req_2       req_2_name
1073  req_3       req_3_name

db2.wafer_types表:-

ID   wafer_type_id    waferType   name
1    1071  req_1       req_1_name
2    1072  req_2       req_2_name
3    1073  req_3       req_3_name

Model(WaferTypesTable)

class WaferTypesTable extends Table {    
    public function initialize(array $config) {
        parent::initialize($config);

        $this->setTable('wafer_types');
        $this->setDisplayField('id');
        $this->setPrimaryKey('id');        
    }
}

Entity(WaferType)

class WaferType extends Entity
{
    protected $_accessible = [
         '*' => true,
        'id' => false
    ];
}

控制器功能:-

public function waferTypeHistory($id,$userid){        
    $waferType = $this->WaferTypes->find()->where(['id'=>$id])->hydrate(false)->toArray();          
    $connection = ConnectionManager::get('default_history');
    $this->WaferTypes->setConnection($connection);
    $waferTypeHistory = $this->WaferTypes->newEntity();        
    $waferTypeHistory = $this->WaferTypes->patchEntity($waferTypeHistory, $waferType[0]);
    $waferTypeHistory->wafer_type_id = $id;
    $this->WaferTypes->save($waferTypeHistory);
    return true;
}

数据已成功插入db2.wafer_types表中。但是Wafer_type_id提交的值是“ 0”。我正在为其分配值,但它始终获得值“ 0”。 知道为什么它每次都会获得值“ 0”。

1 个答案:

答案 0 :(得分:0)

问题可能出在缓存的架构上,db1.wafer_types没有wafer_type_id列,因此ORM不会在保存过程中包括它。

您可以通过在更改连接后取消设置架构来对其进行测试,如下所示:

$this->WaferTypes->setSchema(null);

我建议改为使用单独的(扩展)模型,您可以将其配置为默认使用db2连接。一直在摸索连接和架构似乎是一个不稳定的解决方案。

另请参见