Recent Posts
- (09/10) Fixing Warning: the ECDSA host key for 'github.com' differs from the key for the IP addressTAGS:Web Server Admin
- (12/26) CakePHP 3 - Getting List of Column Definitions from a Table (like schema())TAGS:CakephpCake3
- (09/14) Change Order of Loaded Behaviors in CakePHP 3TAGS:Cake3CakephpWeb ProgrammingPhp
- (05/29) CakePHP 3 - Accept JSON Header Only Working When Debug FalseTAGS:Web ProgrammingCakephpCake3
- (05/23) Remove All Events from Google Calendar (Reset Calendar)TAGS:Web ProgrammingPhp
- (11/08) Google Tag Manager (GTM) Not Firing Default PageView EventTAGS:Web ProgrammingJavascriptGoogle Tag Manager
- (10/13) In PHP, how do you get __toString() Magic Method Result without calling echo?TAGS:CakephpCake3Cakephp 13PhpWeb Programming
- (11/14) Getting output from shell_exec() at all timesTAGS:Web ProgrammingWeb Server Admin
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 18,491 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
Comments for this Posting
Sorry, comments are closed for this posting.
Please Email Kevin if you have any questions. Thanks!
Posted by benny l.e.p
on 17/2/11
thank you this is great tutorial :)