首页 > 解决方案 > 关联来自不同数据库 cakephp 3.0 的表

问题描述

我有两个名为 default 和 default_history 的数据库。以及default数据库下名为users和wafer_detail_history的表和default_history数据库下的order_history。想要将 Users 表与 OrderHistory 表相关联。

订单历史表:-

public function initialize(array $config)
{
    parent::initialize($config);

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

    $this->addBehavior('Timestamp');

    $this->hasMany('WaferDetailHistory', [
        'foreignKey' => 'order_id'
    ]);

    $this->belongsTo('Users', [
        'foreignKey' => 'created_by',
        'joinType' => 'INNER'
    ]);

}

我用这个。

$connection = ConnectionManager::get('default_history');
$this->OrderHistory = TableRegistry::get('OrderHistory');
$this->OrderHistory->setConnection($connection);
$id = 37;
$order_history = $this->OrderHistory->get($id, ['contain' => ['Users']]);

但无法成功。收到此错误:

未找到基表或视图:1146 表“default_history.users”不存在

标签: cakephp-3.0

解决方案


在 OrderHistoryTable.php 文件上试试这个:

$this->setTable('default_history.order_history');

推荐阅读