MainelyDesign.com Blog

Getting a List of Database Tables in CakePHP

Posted on 02/23/2010 at 12:22 pm by Kevin Wentworth
Viewed 12,828 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!):

  1. $db = ConnectionManager::getDataSource('default');
  2. $tables = $db->listSources();
  3. if(in_array('my_table', $tables)) {
  4.     $this->loadModel('MyTable');
  5.     //logic with dynamically loaded model
  6. }

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

Bookmark and Share

Tags for Getting a List of Database Tables in CakePHP

Cakephp | Web Programming | Database | Tutorial | Usage | Errors

Comments for this Posting

Posted by benny l.e.p

on 17/2/11

thank you this is great tutorial :)

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design