杨淇
看了下源码,最终会调用:yii\db\QueryBuilder的createTable方法
public function createTable($table, $columns, $options = null) { $cols = []; foreach ($columns as $name => $type) { if (is_string($name)) { $cols[] = "\t" . $this->db->quoteColumnName($name) . ' ' . $this->getColumnType($type); } else { $cols[] = "\t" . $type; } } $sql = "CREATE TABLE " . $this->db->quoteTableName($table) . " (\n" . implode(",\n", $cols) . "\n)"; return $options === null ? $sql : $sql . ' ' . $options; }
他举了个例子:
$sql = $queryBuilder->createTable('user', [ 'id' => 'pk', 'name' => 'string', 'age' => 'integer', ]);
也就是数组中的key会作为字段,value作为类型,然后得看这个方法getColumnType
public function getColumnType($type) { if ($type instanceof ColumnSchemaBuilder) { $type = $type->__toString(); } if (isset($this->typeMap[$type])) { return $this->typeMap[$type]; } elseif (preg_match('/^(\w+)\((.+?)\)(.*)$/', $type, $matches)) { if (isset($this->typeMap[$matches[1]])) { return preg_replace('/\(.+\)/', '(' . $matches[2] . ')', $this->typeMap[$matches[1]]) . $matches[3]; } } elseif (preg_match('/^(\w+)\s+/', $type, $matches)) { if (isset($this->typeMap[$matches[1]])) { return preg_replace('/^\w+/', $this->typeMap[$matches[1]], $type); } } return $type; }
他首先判断传过来的类型是不是ColumnSchemaBuilder这个对象,如果不是,做一些正则判断,最终返回一个字符串,那反正最终就是构成一个合法的字段声明, 比如:
`phone` int(11) NULL DEFAULT NULL COMMENT '备注' ,
那你可以试试,在构建的时候,直接这样做:
'phone' => 'int(11) NULL DEFAULT NULL COMMENT "备注"'
这样应该也是可行的。具体需要你去试试。
嗯,成功执行 。发现这样做还可以避免遗忘sql基本操作呢
- 杨淇 2016-03-17 已签到连续签到1天,获得了5个金钱
- 杨淇 2016-03-07 已签到连续签到1天,获得了5个金钱
- 杨淇 2016-03-02 已签到连续签到1天,获得了5个金钱
- 杨淇 2016-02-03 已签到连续签到1天,获得了5个金钱