关联来自不同数据库cakephp 3.0的表

时间:2019-01-16 13:52:01

标签: cakephp-3.0

我有两个数据库,名称分别为default和default_history。在默认数据库中,名称为users和wafer_detail_history的表,在default_history数据库中,命名为order_history的表。想要将用户表与OrderHistory表相关联。

OrderHistoryTable:-

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'   不存在

2 个答案:

答案 0 :(得分:0)

在OrderHistoryTable.php文件上尝试一下:

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

答案 1 :(得分:0)

几天前我遇到了同样的问题,

您必须在BelongTo中具有“策略” =>“选择”才能与其他数据库一起加入

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