Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Something like this might do what you're looking for, but does require an extra query per model.</p> <pre><code>&lt;?php class AppModel extends Model { var $create_query = false; function __construct($id = false, $table = null, $ds = null) { parent::__construct($id, $table, $ds); if (!empty($this-&gt;create_query)) { $this-&gt;query($this-&gt;create_query); } } } ?&gt; </code></pre> <p>Then you would just need to add <code>var $create_query = 'CREATE TABLE IF NOT EXISTS ...</code>;` in your models. The <a href="http://dev.mysql.com/doc/refman/5.1/en/create-table.html" rel="nofollow noreferrer">MySQL CREATE TABLE documentation</a> has more information on IF NOT EXISTS.</p> <p><strong>However</strong>, I'm not certain that this isn't trying to call query() too early. Or before the check to see if the table already exists, which it would <strong><em>have</em></strong> to be. Otherwise, CakePHP would error out instead of creating your table. There isn't much documentation on the subject and your best bet for more information going to be to take a look at cake/libs/model/model.php directly.</p> <p><strong>Update: The code above would not work as written.</strong></p> <p>After looking into the Model class a little deeper, Model::__construct calls Model::setSource(). Model::setSource() checks to see if the table exists and throws an error if it doesn't. To use this method, that's where you'd have to override and insert the query. The code below may need to differ, depending on which version of CakePHP you're using.</p> <pre><code>&lt;?php function setSource($tableName) { // From Model::setSource(). I believe this is needed to make query() work. $this-&gt;setDataSource($this-&gt;useDbConfig); // Create our table if we have a create query if (!empty($this-&gt;create_query)) { $this-&gt;query($this-&gt;create_query); } // Now call the parent parent::setSource($tableName); } ?&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload