gpt4 book ai didi

php - CakePHP 可以从模型的 _schema 属性生成我的数据库表吗?

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:56 24 4
gpt4 key购买 nike

当我编写 CakePHP 应用程序时,我的一个常见任务是在运行 bake 之前键入一个 SQL 文件并将其写入数据库以生成一些脚手架。这是我对 CakePHP 的极少数提示之一 - 这样做将我与 MySQL 联系在一起,我想知道是否有更好的方法通过代码来完成它。例如,在某些框架中,我可以定义我的模型使用的列以及数据类型等,然后通过管理界面运行命令以根据代码中显示的内容“构建”数据库。它将在框架后面的任何数据库上执行此操作。

有没有办法让 CakePHP 2.x 可以做这样的事情?我想在我的模型代码中写出数据库模式并运行像 bake 这样的命令来自动生成我需要的表和列。在深入研究食谱文档后,_schema attribute似乎在做我想做的事:

class Post{
public $_schema = array(
'title' => array('type'=>'text'),
'description' => array('type'=>'text'),
'author' => array('type'=>'text')
);
}

但没有示例说明我会从那里做什么。 _schema 属性是否有不同的用途?任何帮助将不胜感激!

最佳答案

不是来自您的 $_schema 数组本身。但是在/APP/Config/Schema 中创建和使用模式文件 schema.php

然后您可以运行烘焙命令“cake schema create”,该命令将“根据模式文件删除和创建表。”

我可能看起来像这样:

class YourSchema extends CakeSchema {

public $addresses = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'length' => 10, 'key' => 'primary'),
'contact_id' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 10),
'type' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
'status' => array('type' => 'integer', 'null' => false, 'default' => '0', 'length' => 2),
'email' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 50, 'collate' => 'utf8_unicode_ci', 'comment' => 'redundant', 'charset' => 'utf8'),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
'tableParameters' => array('charset' => 'utf8', 'collate' => 'utf8_unicode_ci', 'engine' => 'MyISAM')
)

// more tables...
}

关于php - CakePHP 可以从模型的 _schema 属性生成我的数据库表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10393168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com