can CakePHP automatically create tables from models?

你离开我真会死。 提交于 2019-12-09 18:45:39

问题


In python::Pylons i'm able to issue a setup-app command and it will look at my Models and issue the appropriate CREATE TABLE or CREATE INDEX ddl for my particular database.

it seems like this would be a feature in CakePHP, but i'm having trouble finding it.

in fact i see this in the manual: "You can create your database tables as you normally would. When you create your Model classes, they'll automatically map to the tables that you've created."

which leads me to believe it doesn't exist?


回答1:


No, it's other way around - you can create models, controllers and views by having DB schema. It's more logical to have a DB design schema first.

Check this out




回答2:


Some of the comments in the accepted answer above lead me to creating this answer. You can technically create new tables on the fly using the YourModel->query() function. I am currently using this in a Behavior I am writing. This works in CakePHP 2.x, pretty sure it works in 1.3 as well.

In the setup function for the Behavior I am checking to see if the table already exists. If it doesn't I create it.

$dataSource = ConnectionManager::getDataSource('your DB');
if(!in_array($tableName, $dataSource->listSources()){
    $this->createYourTableFunction();
}

In the createYourTableFunction you create a temporary model to run the YourModel->query() against. And just provide it your SQL instructions. When creating your temporary model just set the table parameter to false so you don't get a missing table error.

$YourModel = new Model(array('table' => false, 'name' => 'YourModel', 'ds' => 'Your DB'));
$YourModel->query('SQL instruction string');


来源:https://stackoverflow.com/questions/3455203/can-cakephp-automatically-create-tables-from-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!