Recent Posts
- (02/24) Calling an Element from a Helper TAGS:CakephpWeb ProgrammingUsageTutorialExample
- (10/14) Forcing A Single Join in CakePHP PaginationTAGS:CakephpCakephp 13DatabaseErrorsHabtmMysqlMssqlWeb ProgrammingUsage
- (08/11) Inserting NOW() into MySQL Using CakePHPTAGS:CakephpDatabaseMysqlMssqlWeb ProgrammingUsage
- (08/07) Best PaginateCount for CakePHP - with Group By SupportTAGS:CakephpBehaviorsWeb ProgrammingUsageDatabaseExampleMysqlHabtmHack
- (04/03) CakePHP Error Messages Not Showing on FormTAGS:CakephpCakephp 13Web ProgrammingErrorsUsage
- (02/06) Sorting Paginated Results Using a Related Model Field in CakePHPTAGS:CakephpWeb ProgrammingUsageExample
- (11/02) Changing CakePHP's Model useTable on the FlyTAGS:CakephpWeb ProgrammingMysqlDatabaseExampleTutorial
- (10/18) The Funniest Error Message Ever - Thank You EclipseTAGS:EclipseWeb ProgrammingErrorsHumorWindowsUsageSoftwarePhpCakephp
Subscribe to my feed
MainelyDesign.com Blog
Getting a List of Database Tables in CakePHP
Posted on 02/23/2010 at 12:22 pm by Kevin Wentworth
Viewed 2,909 times | 1 comment
I ran into an interesting problem today. What I wanted to do was know if a table didn't exist in my CakePHP application. What happens- a cakeError is thrown everytime a database table doesn't exist. This is really annoying...I think it would be beneficial to be able to tell Controller::loadModel() to return false instead of an error message. That's not the case. Here's how I got around it (with thanks to Miles Johnson):
Use Cake's Database Connection Manager to Return a List of Database Tables
This works perfectly. The only issue is that now you are dealing with table names instead of Model Names. Not a huge issue, but something to keep in mind. Here's the code to get an array of all the database table names (from anywhere within your application!):
- $db = ConnectionManager::getDataSource('default');
- $tables = $db->listSources();
- $this->loadModel('MyTable');
- //logic with dynamically loaded model
- }
A note about $useTable = false (and why it didn't work for me)
Some of the CakePHP newsgroup postings talk about setting your model's $useTable variable to false. Well that didn't work for me because I needed to dynamically tell if the table existed. There was no way for me to say $this->ModelName->useTable = false. I wasn't going to change the model.php file...a table does exist and I didn't want to tell my application otherwise. Someone mentioned setting it in AppModel, but that just scares me.
Cheers,
-Kevin Wentworth
Tags for Getting a List of Database Tables in CakePHP
Cakephp | Web Programming | Database | Tutorial | Usage | Errors

Posted by benny l.e.p
on 17/2/11
thank you this is great tutorial :)