杨淇

杨淇

争取早日造轮子。

  • 财富值5620
  • 威望值10
  • 总积分6230

个人信息

  • 回复了 的回答

    看了下源码,最终会调用: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基本操作呢

  • 回复了 的回答

    之前的方法还能接着用吧?

    可以的,向下兼容

  • 回复了 的回答

    你是不是希望有个->comment('xxx')方法啊 哈哈,好吧,这种非标准的语法不兼容其他数据库,所以yii没提供,只能自己按照你前一种写了,

    嗯嗯,聪明如你

  • 回复了 的回答

    2.0.7不支持之前版本的实现了?是不能那样用了吗?

    向下兼容的,觉得新方法用起来更直观

  • 2016-03-17 已签到
    连续签到1天,获得了5个金钱
  • 2016-03-07 已签到
    连续签到1天,获得了5个金钱
  • 2016-03-02 已签到
    连续签到1天,获得了5个金钱
  • 2016-02-03 已签到
    连续签到1天,获得了5个金钱
副总裁 等级规则
6230/10000
资料完整度
70/100
用户活跃度
0/100

Ta的关注

15

Ta的粉丝

12

Ta的访客

30