can CakePHP automatically create tables from model

2020-07-23 06:31发布

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?

2条回答
冷血范
2楼-- · 2020-07-23 07:09

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');
查看更多
我命由我不由天
3楼-- · 2020-07-23 07:27

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

查看更多
登录 后发表回答