gpt4 book ai didi

php - 在 CakePHP 3 中动态动态添加现有表中的列

转载 作者:行者123 更新时间:2023-12-03 00:11:29 25 4
gpt4 key购买 nike

我想在 CakePHP 3 的现有表中添加列。

我的ContactsTable.php文件代码:

<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Migrations\AbstractMigration;

class ContactsTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('Timestamp');
$table = $this->table('contacts');
$table->addColumn('price', 'decimal')->update();

}
}

我已经按照 CakePHP 3 文档中的描述进行了尝试,但出现了此错误:

Call to a member function addColumn() on a non-object

如何通过 Controller 即时添加列?

最佳答案

代码:

<?php

namespace App\Controller;

use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
use Cake\Database\Schema\Table;
use Cake\Datasource\ConnectionManager;
use \Migrations\AbstractMigration as AbstractMigration;
use \Phinx\Db\Adapter\MysqlAdapter as MysqlAdapter;

class PagesController extends AppController
{
public function display()
{
$connectionArray = ConnectionManager::get('default')->config();
$connectionArray['pass'] = $connectionArray['password'];
$connectionArray['user'] = $connectionArray['username'];
$connectionArray['name'] = $connectionArray['database'];

$migrationObject = new AbstractMigration(mt_rand());
$migrationObject->setAdapter(new MysqlAdapter($connectionArray));
$tree = $migrationObject->table('tests');


$tree->addColumn('something', 'text')
->update();
}
}

经过几个小时的黑客攻击,终于找到了一种即时执行此操作的方法。

在默认的 cakephp 3 中测试(最新 - 截至今天 - 2016 年 6 月 2 日)

如果您使用不同的数据库适配器,请将其更改为 MysqlAdapter 中的适配器。

Note to the users:

  • This is an ugly hack and should be used ONLY if you do not work inan organization where each migration commit requires peer reference.

  • mt_rand() must NEVER be used as a version number hack.

  • There is no canonical way of doing it via the controllers. Update in a datasource MUST always be done modified via migrations - using a proper structure.

  • Refer to Running Migrations in a non-shell environment and try to create a migrations logs under /config/migrations, that would be more rule-specific-on-the-fly and you will also have logs for peers to review.

关于php - 在 CakePHP 3 中动态动态添加现有表中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37362123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com