关联来自不同数据库的表 cakephp 3.0
Associate tables from different database cakephp 3.0
我有两个数据库,名称分别为 default 和 default_history。并且 tables 名称为 users,默认数据库下为 wafer_detail_history,default_history 数据库下为 order_history。想要将 Users table 与 OrderHistory table.
相关联
订单历史表:-
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']]);
但无法成功。收到此错误:
Base table or view not found: 1146 Table 'default_history.users'
doesn't exist
在 OrderHistoryTable.php 文件上试试这个:
$this->setTable('default_history.order_history');
几天前我遇到了同样的问题,
您的 BelongTo 中必须有 'strategy' => 'select' 才能加入其他数据库
$this->belongsTo('Users', [
'strategy' => 'select'
'foreignKey' => 'created_by',
'joinType' => 'INNER'
]);
我有两个数据库,名称分别为 default 和 default_history。并且 tables 名称为 users,默认数据库下为 wafer_detail_history,default_history 数据库下为 order_history。想要将 Users table 与 OrderHistory table.
相关联订单历史表:-
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']]);
但无法成功。收到此错误:
Base table or view not found: 1146 Table 'default_history.users' doesn't exist
在 OrderHistoryTable.php 文件上试试这个:
$this->setTable('default_history.order_history');
几天前我遇到了同样的问题,
您的 BelongTo 中必须有 'strategy' => 'select' 才能加入其他数据库
$this->belongsTo('Users', [
'strategy' => 'select'
'foreignKey' => 'created_by',
'joinType' => 'INNER'
]);