CakePHP can't find table after creating a tabl

2019-09-05 02:39发布

问题:

I create a table directly by a query. I only want to Import some data. Therefor i execute a query which is built dynamicly and i try execute this query in a Component-class. (I use a random existing model to execute this query is there a better why?)

$query= "CREATE TABLE IF NOT EXISTS testerdbs (
'Ü1' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü2' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü3' int(3) DEFAULT NULL,
'Ü4' varchar(6) COLLATE utf8_swedish_ci DEFAULT NULL,
'Ü5' date DEFAULT NULL
)"
$data = ClassRegistry::init('import_files');
$data->query($query);

This works fine. In the same request i want to access the created table in the controller.

App::import('Model', "testerdb");
//$this->loadModel("testerdb");
$newTable = ClassRegistry::init("testerdb");
echo '<pre>', print_r($newTable->getColumnTypes()), '</pre>';

If I try to execute this in same request i always get the error:

Error: Table testerdbs for model testerdb was not found in datasource default.

If I do exactly the same request again, everything works fine... I google about an hour and it seemed that cake cache the model. If I execute this request again cake cache again all the tables and than cake find my new table. So I hoped to load or import the created Table in the same request, but i don't work.

Is there another way to load the table? Where is my mistake?

Thanks for help!

回答1:

This might be a bit stale, but I just spent the last week trying to work around the problem and maybe this will help someone.

The root problem is that the cache of table names is initialized before you created the temporary table, so the 'setSource' function returns an error that the temporary table does not exist.

The solution is to overrid the 'setSource' function for the Model that you are creating for 'testerdb' and remove the check on table existence (i.e. everything within the test:

if (method_exists($db, 'listSources'))' )

Your model definition should look something like this:

App::uses('AppModel', 'Model');
class testerdb extends AppModel {
public function setSource($tableName) {
    $this->setDataSource($this->useDbConfig);
    $db = ConnectionManager::getDataSource($this->useDbConfig);
    $this->table = $this->useTable = $tableName;
    $this->tableToModel[$this->table] = $this->alias;
    $this->schema();  
    }
}

Many thanks to whomever posted the link below. This has worked with my CakePHP 2.0 instance. http://web2.0goodies.com/blog/uncategorized/mysql-temporary-tables-and-cakephp-1-3/



回答2:

Why would you only want to have a temporary table? I would just temporarily store whatever data you are importing in an in-memory model or data-structure.

If the table is not temporary, then just create it statically before you run your program.