问题
But it will give return same data from tab[1] only.. i want to get data from tab[1] and tab[0] distinctly
$db = ConnectionManager::getDataSource('default');
$tab = $db->listSources();
echo '<br>';
$this->Form->useTable=$tab[1];
print_r($this->Form->find(`all'));
echo '<br>';
$this->Form->use Table=$tab[0];
print_r($this->Form->find('all'));
回答1:
Changing Model->useTable
at runtime does not work properly because once a model has been initialised, CakePHP caches the schema of the database-table.
To switch to another table and clear the cached schema, use Model->setSource('tablename')
Documentation; http://api.cakephp.org/2.3/source-class-Model.html#1100-1125
Your example will then look like this;
echo '<br>';
$this->Form->setSource($tab[1]);
print_r($this->Form->find(`all'));
echo '<br>';
$this->Form->setSource($tab[0]);
print_r($this->Form->find('all'));
Also, please use debug()
to output results for debugging in stead of print_r()
. This will output the results properly formatted. (You'll need to set debug to 1 or higher inside your app/Config/core.php configuration for debug() to work)
however
Switching the sourcetable of a Model is generally bad practice and will only apply to very specific cases. I would strongly suggest to create a separate model for each database table.
来源:https://stackoverflow.com/questions/15403655/how-to-get-data-from-two-different-table-in-cake-php