我的数据库中有一个表“assets”(id、name、serial),外部数据库(在app.php中声明)中存储了一个只读表资产(大写)(id、name、serial)
在我的app.php,我把连接:
'Datasources' => [
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db1',
'encoding' => 'utf8',
'quoteIdentifiers' => false,
'url' => env('DATABASE_URL', null),
],
'external_db' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Mysql',
'persistent' => false,
'host' => 'domain.com',
'port' => '3306',
'username' => 'my_user',
'password' => 'my_password',
'database' => 'db2',
'encoding' => 'utf8',
'timezone' => 'UTC',
'flags' => [],
'cacheMetadata' => false,
'quoteIdentifiers' => false,
'log' => false,
'url' => env('DATABASE_URL', null),
],
我能够:烘焙所有资产(从默认数据库)。因为cake bake all不支持大写,所以我手动创建了:ExternalAssetTable。php:
class ExternalAssetsTable extends Table {
public function initialize(array $config)
{
parent::initialize($config);
$this->ExternalAsset->setDataSource('external_db');
$this->setTable('ASSET');
$this->setDisplayField('NAME');
$this->setPrimaryKey('ID');
然后,我尝试使用以下内容创建控制器和模板视图:
cake bake controller external_assets
cake bake template external_assets
和:蛋糕烘焙控制器资产-c外部_db蛋糕烘焙模板资产-c外部_db
代码也不起作用。
我的第一个问题:我的代码出了什么问题?
我的第二个需要是:
“资产”包含从资产导入的数据,以及在我的数据库中手动输入的其他数据。
SERIAL可能会偶尔改变,我需要将其导入到资产中。
在资产指数中。ctp和视图。ctp,我需要显示以下列:id、名称、序列号和相应的资产。名字,资产。序列号,如果存在的话。
我试图添加一个函数在AssetsController.php
public function getRemoteData(){
$conn1 = ConnectionManager::get('k1000db'); #Remote Database 1
$sql = "SELECT * FROM ASSET";
$query = $conn1->prepare($sql);
$query->execute();
$result = $query->fetchAll(); #Here is the result
}
我的问题是:如何在AssetsController index(),view()函数中调用此函数,并在Assetindex.ctp中调用此函数?
非常感谢你的帮助。
在你的第一个问题中:
蛋糕烘焙
使所有内容都基于数据库中的表,因此,您的代码是:
cake bake ASSETS -c your_external_db_here
如果使用上面的代码,您将检查Cakephp可以烘焙的所有表:
cake bake -c your_external_db_here
完成后,手动将资产重命名为
ExternalAssets
,在Controller
、Template文件夹
和您烘焙的其他东西,以更好地识别表。但是要小心,这个蛋糕烘焙
不会取代您以前烘焙的其他资产。
在第二个问题中:
您将在您的资产负债表中建立一个关联
:
public function initialize(array $config)
{
parent::initialize($config);
$this->hasOne('ExternalAssets')->setForeignKey('fk_here')->('pk_here');
}
在控制器中:
public function index()
{
$assets = $this->Assets->find('all')
->select([ 'id', 'name', 'serial'])
->contain(['ExternalAssets' => [
'fields' => [
'NAME','SERIAL'
]
]);
//if you wanna paginate your resut
//$assets = $this->paginate($assets);
$this->set(compact('assets'));
$this->set('_serialize', ['assets']);
}
public function view($id = null)
{
$assets= $this->Assets->get($id, [
'contain' => []
]);
$this->set('assets', $assets);
$this->set('_serialize', ['assets']);
}
我不可能烤外部桌子,因为它不尊重cakephp惯例。作为替代,我在index()中使用了这个:
$connection = ConnectionManager::get('db2');
$machines = $connection->execute('SELECT * FROM MACHINE ORDER BY NAME ASC');
$this->set(compact('machines'));
$this->set('_serialize', ['machines']);
然后,我手动创建了视图。