Home >php教程 >php手册 >实现利用ThinkPHP中定义的model直接创建表

实现利用ThinkPHP中定义的model直接创建表

WBOY
WBOYOriginal
2016-06-07 11:41:301518browse

方便调试测试,或者做实验
Model.Class.PHP
DB.Class.PHP
两个文件中增加了createTable的代码
使用示例:
$user = D('Object');
$return = $user->createTable();
Model.Class.PHP 增加以下代码
/**
* 创建表
* @access public
*/
public function createTable()
{
$fields = $this->fields;
if(empty($fields))
{
return false;
}
$types = $fields["_type"];
if(empty($types))
{
return false;
}
$mainKey = $fields["_pk"];
unset($fields["_type"]);
unset($fields["_pk"]);
$fields = array_values($fields);
if(count($fields) != count($types))
{
return false;
}
$options = array();
$options = $this->_parseOptions($options);
return $this->db->createTable($options,$fields, $types, $mainKey);
}

DB.Class.PHP 增加以下代码
/**
* 创建表
* @access public
*/
public function createTable($options,$files,$types,$mainKey)
{
$this->model = $options['model'];
$sql = "CREATE TABLE ".$this->parseTable($options['table'])."(";
$types = $this->parseTypes($types);
if($types === false)
{
log("functrion createTable,类型错误,请检查".$this->model.".class.php数据模型定义");
return false;
}
$hasMainKey = false;
$i=1;
$count = count($files);
foreach($files as &$value)
{
$sql .= $value . " " . $types[$value];
if($value === $mainKey)
{
$hasMainKey = true;
$sql .= " PRIMARY KEY";
}
if($i {
$sql .= ",";
}
++$i;
}
unset($value);
$sql .= ")";
if(!$hasMainKey && !empty($mainKey))
{
log("functrion createTable,定义的主键名未包含在列名中");
return false;
}
return $this->execute($sql);
}

AD:真正免费,域名+虚机+企业邮箱=0元

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn