system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CDbCommandBuilder

system.db.schema
继承 class CDbCommandBuilder » CComponent
子类 CMssqlCommandBuilder, CMysqlCommandBuilder, COciCommandBuilder, CPgsqlCommandBuilder, CSqliteCommandBuilder
可用自 1.0
源码 framework/db/schema/CDbCommandBuilder.php
CDbCommandBuilder provides basic methods to create query commands for tables.

公共属性

隐藏继承的属性

属性类型描述被定义在
dbConnection CDbConnection database connection. CDbCommandBuilder
schema CDbSchema the schema for this command builder. CDbCommandBuilder

受保护的属性

隐藏继承的属性

属性类型描述被定义在
integerPrimaryKeyDefaultValue string Returns default value of the integer/serial primary key. Default value means that the next CDbCommandBuilder

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__construct() CDbCommandBuilder
__get() Returns a property value, an event handler list or a behavior based on its name. CComponent
__isset() Checks if a property value is null. CComponent
__set() Sets value of a component property. CComponent
__unset() Sets a component property to be null. CComponent
applyCondition() Alters the SQL to apply WHERE clause. CDbCommandBuilder
applyGroup() Alters the SQL to apply GROUP BY. CDbCommandBuilder
applyHaving() Alters the SQL to apply HAVING. CDbCommandBuilder
applyJoin() Alters the SQL to apply JOIN clause. CDbCommandBuilder
applyLimit() Alters the SQL to apply LIMIT and OFFSET. CDbCommandBuilder
applyOrder() Alters the SQL to apply ORDER BY. CDbCommandBuilder
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
bindValues() Binds parameter values for an SQL command. CDbCommandBuilder
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
createColumnCriteria() Creates a query criteria with the specified column values. CDbCommandBuilder
createCountCommand() Creates a COUNT(*) command for a single table. CDbCommandBuilder
createCriteria() Creates a query criteria. CDbCommandBuilder
createDeleteCommand() Creates a DELETE command. CDbCommandBuilder
createFindCommand() Creates a SELECT command for a single table. CDbCommandBuilder
createInCondition() Generates the expression for selecting rows of specified primary key values. CDbCommandBuilder
createInsertCommand() Creates an INSERT command. CDbCommandBuilder
createMultipleInsertCommand() Creates a multiple INSERT command. CDbCommandBuilder
createPkCondition() Generates the expression for selecting rows of specified primary key values. CDbCommandBuilder
createPkCriteria() Creates a query criteria with the specified primary key. CDbCommandBuilder
createSearchCondition() Generates the expression for searching the specified keywords within a list of columns. CDbCommandBuilder
createSqlCommand() Creates a command based on a given SQL statement. CDbCommandBuilder
createUpdateCommand() Creates an UPDATE command. CDbCommandBuilder
createUpdateCounterCommand() Creates an UPDATE command that increments/decrements certain columns. CDbCommandBuilder
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getDbConnection() Returns database connection. CDbCommandBuilder
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getLastInsertID() Returns the last insertion ID for the specified table. CDbCommandBuilder
getSchema() Returns the schema for this command builder. CDbCommandBuilder
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasProperty() Determines whether a property is defined. CComponent
raiseEvent() Raises an event. CComponent

受保护的方法

隐藏继承的方法

方法描述被定义在
composeMultipleInsertCommand() Creates a multiple INSERT command. CDbCommandBuilder
createCompositeInCondition() Generates the expression for selecting rows with specified composite key values. CDbCommandBuilder
ensureTable() Checks if the parameter is a valid table schema. CDbCommandBuilder
getIntegerPrimaryKeyDefaultValue() Returns default value of the integer/serial primary key. Default value means that the next CDbCommandBuilder

属性详情

dbConnection 属性 只读

database connection.

integerPrimaryKeyDefaultValue 属性 只读 (自版本 v1.1.14 可用)

Returns default value of the integer/serial primary key. Default value means that the next autoincrement/sequence value would be used.

schema 属性 只读

the schema for this command builder.

方法详情

__construct() 方法
public void __construct(CDbSchema $schema)
$schema CDbSchema the schema for this command builder
源码: framework/db/schema/CDbCommandBuilder.php#31 (显示)
public function __construct($schema)
{
    
$this->_schema=$schema;
    
$this->_connection=$schema->getDbConnection();
}

applyCondition() 方法
public string applyCondition(string $sql, string $condition)
$sql string the SQL statement without WHERE clause
$condition string the WHERE clause (without WHERE keyword)
{return} string the altered SQL statement
源码: framework/db/schema/CDbCommandBuilder.php#481 (显示)
public function applyCondition($sql,$condition)
{
    if(
$condition!='')
        return 
$sql.' WHERE '.$condition;
    else
        return 
$sql;
}

Alters the SQL to apply WHERE clause.

applyGroup() 方法
public string applyGroup(string $sql, string $group)
$sql string SQL query string without GROUP BY.
$group string GROUP BY
{return} string SQL with GROUP BY.
源码: framework/db/schema/CDbCommandBuilder.php#526 (显示)
public function applyGroup($sql,$group)
{
    if(
$group!='')
        return 
$sql.' GROUP BY '.$group;
    else
        return 
$sql;
}

Alters the SQL to apply GROUP BY.

applyHaving() 方法
public string applyHaving(string $sql, string $having)
$sql string SQL query string without HAVING
$having string HAVING
{return} string SQL with HAVING
源码: framework/db/schema/CDbCommandBuilder.php#540 (显示)
public function applyHaving($sql,$having)
{
    if(
$having!='')
        return 
$sql.' HAVING '.$having;
    else
        return 
$sql;
}

Alters the SQL to apply HAVING.

applyJoin() 方法
public string applyJoin(string $sql, string $join)
$sql string the SQL statement to be altered
$join string the JOIN clause (starting with join type, such as INNER JOIN)
{return} string the altered SQL statement
源码: framework/db/schema/CDbCommandBuilder.php#467 (显示)
public function applyJoin($sql,$join)
{
    if(
$join!='')
        return 
$sql.' '.$join;
    else
        return 
$sql;
}

Alters the SQL to apply JOIN clause.

applyLimit() 方法
public string applyLimit(string $sql, integer $limit, integer $offset)
$sql string SQL query string without LIMIT and OFFSET.
$limit integer maximum number of rows, -1 to ignore limit.
$offset integer row offset, -1 to ignore offset.
{return} string SQL with LIMIT and OFFSET
源码: framework/db/schema/CDbCommandBuilder.php#511 (显示)
public function applyLimit($sql,$limit,$offset)
{
    if(
$limit>=0)
        
$sql.=' LIMIT '.(int)$limit;
    if(
$offset>0)
        
$sql.=' OFFSET '.(int)$offset;
    return 
$sql;
}

Alters the SQL to apply LIMIT and OFFSET. Default implementation is applicable for PostgreSQL, MySQL, MariaDB and SQLite.

applyOrder() 方法
public string applyOrder(string $sql, string $orderBy)
$sql string SQL statement without ORDER BY.
$orderBy string column ordering
{return} string modified SQL applied with ORDER BY.
源码: framework/db/schema/CDbCommandBuilder.php#495 (显示)
public function applyOrder($sql,$orderBy)
{
    if(
$orderBy!='')
        return 
$sql.' ORDER BY '.$orderBy;
    else
        return 
$sql;
}

Alters the SQL to apply ORDER BY.

bindValues() 方法
public void bindValues(CDbCommand $command, array $values)
$command CDbCommand database command
$values array values for binding (integer-indexed array for question mark placeholders, string-indexed array for named placeholders)
源码: framework/db/schema/CDbCommandBuilder.php#553 (显示)
public function bindValues($command$values)
{
    if((
$n=count($values))===0)
        return;
    if(isset(
$values[0])) // question mark placeholders
    
{
        for(
$i=0;$i<$n;++$i)
            
$command->bindValue($i+1,$values[$i]);
    }
    else 
// named placeholders
    
{
        foreach(
$values as $name=>$value)
        {
            if(
$name[0]!==':')
                
$name=':'.$name;
            
$command->bindValue($name,$value);
        }
    }
}

Binds parameter values for an SQL command.

composeMultipleInsertCommand() 方法
protected CDbCommand composeMultipleInsertCommand(mixed $table, array $data, array $templates=array ( ))
$table mixed the table schema (CDbTableSchema) or the table name (string).
$data array list data to be inserted, each value should be an array in format (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
$templates array templates for the SQL parts.
{return} CDbCommand multiple insert command
源码: framework/db/schema/CDbCommandBuilder.php#278 (显示)
protected function composeMultipleInsertCommand($table,array $data,array $templates=array())
{
    if (empty(
$data))
        throw new 
CDbException(Yii::t('yii','Can not generate multiple insert command with empty data set.'));
    
$templates=array_merge(
        array(
            
'main'=>'INSERT INTO {{tableName}} ({{columnInsertNames}}) VALUES {{rowInsertValues}}',
            
'columnInsertValue'=>'{{value}}',
            
'columnInsertValueGlue'=>', ',
            
'rowInsertValue'=>'({{columnInsertValues}})',
            
'rowInsertValueGlue'=>', ',
            
'columnInsertNameGlue'=>', ',
        ),
        
$templates
    
);
    
$this->ensureTable($table);
    
$tableName=$table->rawName;
    
$params=array();
    
$columnInsertNames=array();
    
$rowInsertValues=array();

    
$columns=array();
    foreach(
$data as $rowData)
    {
        foreach(
$rowData as $columnName=>$columnValue)
        {
            if(!
in_array($columnName,$columns,true))
                if(
$table->getColumn($columnName)!==null)
                    
$columns[]=$columnName;
        }
    }
    foreach(
$columns as $name)
        
$columnInsertNames[$name]=$this->getDbConnection()->quoteColumnName($name);
    
$columnInsertNamesSqlPart=implode($templates['columnInsertNameGlue'],$columnInsertNames);

    foreach(
$data as $rowKey=>$rowData)
    {
        
$columnInsertValues=array();
        foreach(
$columns as $columnName)
        {
            
$column=$table->getColumn($columnName);
            
$columnValue=array_key_exists($columnName,$rowData) ? $rowData[$columnName] : new CDbExpression('NULL');
            if(
$columnValue instanceof CDbExpression)
            {
                
$columnInsertValue=$columnValue->expression;
                foreach(
$columnValue->params as $columnValueParamName=>$columnValueParam)
                    
$params[$columnValueParamName]=$columnValueParam;
            }
            else
            {
                
$columnInsertValue=':'.$columnName.'_'.$rowKey;
                
$params[':'.$columnName.'_'.$rowKey]=$column->typecast($columnValue);
            }
            
$columnInsertValues[]=strtr($templates['columnInsertValue'],array(
                
'{{column}}'=>$columnInsertNames[$columnName],
                
'{{value}}'=>$columnInsertValue,
            ));
        }
        
$rowInsertValues[]=strtr($templates['rowInsertValue'],array(
            
'{{tableName}}'=>$tableName,
            
'{{columnInsertNames}}'=>$columnInsertNamesSqlPart,
            
'{{columnInsertValues}}'=>implode($templates['columnInsertValueGlue'],$columnInsertValues)
        ));
    }

    
$sql=strtr($templates['main'],array(
        
'{{tableName}}'=>$tableName,
        
'{{columnInsertNames}}'=>$columnInsertNamesSqlPart,
        
'{{rowInsertValues}}'=>implode($templates['rowInsertValueGlue'], $rowInsertValues),
    ));
    
$command=$this->getDbConnection()->createCommand($sql);

    foreach(
$params as $name=>$value)
        
$command->bindValue($name,$value);

    return 
$command;
}

Creates a multiple INSERT command. This method compose the SQL expression via given part templates, providing ability to adjust command for different SQL syntax.

createColumnCriteria() 方法
public CDbCriteria createColumnCriteria(mixed $table, array $columns, mixed $condition='', array $params=array ( ), string $prefix=NULL)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$columns array column values that should be matched in the query (name=>value)
$condition mixed query condition or criteria. If a string, it is treated as query condition; If an array, it is treated as the initial values for constructing a CDbCriteria; Otherwise, it should be an instance of CDbCriteria.
$params array parameters to be bound to an SQL statement. This is only used when the third parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
$prefix string column prefix (ended with dot). If null, it will be the table name
{return} CDbCriteria the created query criteria
源码: framework/db/schema/CDbCommandBuilder.php#661 (显示)
public function createColumnCriteria($table,$columns,$condition='',$params=array(),$prefix=null)
{
    
$this->ensureTable($table);
    
$criteria=$this->createCriteria($condition,$params);
    if(
$criteria->alias!='')
        
$prefix=$this->_schema->quoteTableName($criteria->alias).'.';
    
$bindByPosition=isset($criteria->params[0]);
    
$conditions=array();
    
$values=array();
    
$i=0;
    if(
$prefix===null)
        
$prefix=$table->rawName.'.';
    foreach(
$columns as $name=>$value)
    {
        if((
$column=$table->getColumn($name))!==null)
        {
            if(
is_array($value))
                
$conditions[]=$this->createInCondition($table,$name,$value,$prefix);
            elseif(
$value!==null)
            {
                if(
$bindByPosition)
                {
                    
$conditions[]=$prefix.$column->rawName.'=?';
                    
$values[]=$value;
                }
                else
                {
                    
$conditions[]=$prefix.$column->rawName.'='.self::PARAM_PREFIX.$i;
                    
$values[self::PARAM_PREFIX.$i]=$value;
                    
$i++;
                }
            }
            else
                
$conditions[]=$prefix.$column->rawName.' IS NULL';
        }
        else
            throw new 
CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
                array(
'{table}'=>$table->name,'{column}'=>$name)));
    }
    
$criteria->params=array_merge($values,$criteria->params);
    if(isset(
$conditions[0]))
    {
        if(
$criteria->condition!='')
            
$criteria->condition=implode(' AND ',$conditions).' AND ('.$criteria->condition.')';
        else
            
$criteria->condition=implode(' AND ',$conditions);
    }
    return 
$criteria;
}

Creates a query criteria with the specified column values.

createCompositeInCondition() 方法
protected string createCompositeInCondition(CDbTableSchema $table, array $values, string $prefix)
$table CDbTableSchema the table schema
$values array list of primary key values to be selected within
$prefix string column prefix (ended with dot)
{return} string the expression for selection
源码: framework/db/schema/CDbCommandBuilder.php#841 (显示)
protected function createCompositeInCondition($table,$values,$prefix)
{
    
$keyNames=array();
    foreach(
array_keys($values[0]) as $name)
        
$keyNames[]=$prefix.$table->columns[$name]->rawName;
    
$vs=array();
    foreach(
$values as $value)
        
$vs[]='('.implode(', ',$value).')';
    return 
'('.implode(', ',$keyNames).') IN ('.implode(', ',$vs).')';
}

Generates the expression for selecting rows with specified composite key values.

createCountCommand() 方法
public CDbCommand createCountCommand(mixed $table, CDbCriteria $criteria, string $alias='t')
$table mixed the table schema (CDbTableSchema) or the table name (string).
$criteria CDbCriteria the query criteria
$alias string the alias name of the primary table. Defaults to 't'.
{return} CDbCommand query command.
源码: framework/db/schema/CDbCommandBuilder.php#111 (显示)
public function createCountCommand($table,$criteria,$alias='t')
{
    
$this->ensureTable($table);
    if(
$criteria->alias!='')
        
$alias=$criteria->alias;
    
$alias=$this->_schema->quoteTableName($alias);

    if(!empty(
$criteria->group) || !empty($criteria->having))
    {
        
$select=is_array($criteria->select) ? implode(', ',$criteria->select) : $criteria->select;
        if(
$criteria->alias!='')
            
$alias=$criteria->alias;
        
$sql=($criteria->distinct 'SELECT DISTINCT':'SELECT').{$select} FROM {$table->rawName} $alias";
        
$sql=$this->applyJoin($sql,$criteria->join);
        
$sql=$this->applyCondition($sql,$criteria->condition);
        
$sql=$this->applyGroup($sql,$criteria->group);
        
$sql=$this->applyHaving($sql,$criteria->having);
        
$sql="SELECT COUNT(*) FROM ($sql) sq";
    }
    else
    {
        if(
is_string($criteria->select) && stripos($criteria->select,'count')===0)
            
$sql="SELECT ".$criteria->select;
        elseif(
$criteria->distinct)
        {
            if(
is_array($table->primaryKey))
            {
                
$pk=array();
                foreach(
$table->primaryKey as $key)
                    
$pk[]=$alias.'.'.$this->_schema->quoteColumnName($key);
                
$pk=implode(', ',$pk);
            }
            else
                
$pk=$alias.'.'.$this->_schema->quoteColumnName($table->primaryKey);
            
$sql="SELECT COUNT(DISTINCT $pk)";
        }
        else
            
$sql="SELECT COUNT(*)";
        
$sql.=" FROM {$table->rawName} $alias";
        
$sql=$this->applyJoin($sql,$criteria->join);
        
$sql=$this->applyCondition($sql,$criteria->condition);
    }

    
// Suppress binding of parameters belonging to the ORDER clause. Issue #1407.
    
if($criteria->order && $criteria->params)
    {
        
$params1=array();
        
preg_match_all('/(:\w+)/',$sql,$params1);
        
$params2=array();
        
preg_match_all('/(:\w+)/',$this->applyOrder($sql,$criteria->order),$params2);
        foreach(
array_diff($params2[0],$params1[0]) as $param)
            unset(
$criteria->params[$param]);
    }

    
// Do the same for SELECT part.
    
if($criteria->select && $criteria->params)
    {
        
$params1=array();
        
preg_match_all('/(:\w+)/',$sql,$params1);
        
$params2=array();
        
preg_match_all('/(:\w+)/',$sql.' '.(is_array($criteria->select) ? implode(', ',$criteria->select) : $criteria->select),$params2);
        foreach(
array_diff($params2[0],$params1[0]) as $param)
            unset(
$criteria->params[$param]);
    }

    
$command=$this->_connection->createCommand($sql);
    
$this->bindValues($command,$criteria->params);
    return 
$command;
}

Creates a COUNT(*) command for a single table.

createCriteria() 方法
public CDbCriteria createCriteria(mixed $condition='', array $params=array ( ))
$condition mixed query condition or criteria. If a string, it is treated as query condition (the WHERE clause); If an array, it is treated as the initial values for constructing a CDbCriteria object; Otherwise, it should be an instance of CDbCriteria.
$params array parameters to be bound to an SQL statement. This is only used when the first parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
{return} CDbCriteria the created query criteria
源码: framework/db/schema/CDbCommandBuilder.php#585 (显示)
public function createCriteria($condition='',$params=array())
{
    if(
is_array($condition))
        
$criteria=new CDbCriteria($condition);
    elseif(
$condition instanceof CDbCriteria)
        
$criteria=clone $condition;
    else
    {
        
$criteria=new CDbCriteria;
        
$criteria->condition=$condition;
        
$criteria->params=$params;
    }
    return 
$criteria;
}

Creates a query criteria.

createDeleteCommand() 方法
public CDbCommand createDeleteCommand(mixed $table, CDbCriteria $criteria)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$criteria CDbCriteria the query criteria
{return} CDbCommand delete command.
源码: framework/db/schema/CDbCommandBuilder.php#187 (显示)
public function createDeleteCommand($table,$criteria)
{
    
$this->ensureTable($table);
    
$sql="DELETE FROM {$table->rawName}";
    
$sql=$this->applyJoin($sql,$criteria->join);
    
$sql=$this->applyCondition($sql,$criteria->condition);
    
$sql=$this->applyGroup($sql,$criteria->group);
    
$sql=$this->applyHaving($sql,$criteria->having);
    
$sql=$this->applyOrder($sql,$criteria->order);
    
$sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
    
$command=$this->_connection->createCommand($sql);
    
$this->bindValues($command,$criteria->params);
    return 
$command;
}

Creates a DELETE command.

createFindCommand() 方法
public CDbCommand createFindCommand(mixed $table, CDbCriteria $criteria, string $alias='t')
$table mixed the table schema (CDbTableSchema) or the table name (string).
$criteria CDbCriteria the query criteria
$alias string the alias name of the primary table. Defaults to 't'.
{return} CDbCommand query command.
源码: framework/db/schema/CDbCommandBuilder.php#74 (显示)
public function createFindCommand($table,$criteria,$alias='t')
{
    
$this->ensureTable($table);
    
$select=is_array($criteria->select) ? implode(', ',$criteria->select) : $criteria->select;
    if(
$criteria->alias!='')
        
$alias=$criteria->alias;
    
$alias=$this->_schema->quoteTableName($alias);

    
// issue 1432: need to expand * when SQL has JOIN
    
if($select==='*' && !empty($criteria->join))
    {
        
$prefix=$alias.'.';
        
$select=array();
        foreach(
$table->getColumnNames() as $name)
            
$select[]=$prefix.$this->_schema->quoteColumnName($name);
        
$select=implode(', ',$select);
    }

    
$sql=($criteria->distinct 'SELECT DISTINCT':'SELECT').{$select} FROM {$table->rawName} $alias";
    
$sql=$this->applyJoin($sql,$criteria->join);
    
$sql=$this->applyCondition($sql,$criteria->condition);
    
$sql=$this->applyGroup($sql,$criteria->group);
    
$sql=$this->applyHaving($sql,$criteria->having);
    
$sql=$this->applyOrder($sql,$criteria->order);
    
$sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
    
$command=$this->_connection->createCommand($sql);
    
$this->bindValues($command,$criteria->params);
    return 
$command;
}

Creates a SELECT command for a single table.

createInCondition() 方法
public string createInCondition(mixed $table, mixed $columnName, array $values, string $prefix=NULL)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$columnName mixed the column name(s). It can be either a string indicating a single column or an array of column names. If the latter, it stands for a composite key.
$values array list of key values to be selected within
$prefix string column prefix (ended with dot). If null, it will be the table name
{return} string the expression for selection
源码: framework/db/schema/CDbCommandBuilder.php#763 (显示)
public function createInCondition($table,$columnName,$values,$prefix=null)
{
    if((
$n=count($values))<1)
        return 
'0=1';

    
$this->ensureTable($table);

    if(
$prefix===null)
        
$prefix=$table->rawName.'.';

    
$db=$this->_connection;

    if(
is_array($columnName) && count($columnName)===1)
        
$columnName=reset($columnName);

    if(
is_string($columnName)) // simple key
    
{
        if(!isset(
$table->columns[$columnName]))
            throw new 
CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
            array(
'{table}'=>$table->name'{column}'=>$columnName)));
        
$column=$table->columns[$columnName];

        
$values=array_values($values);
        foreach(
$values as &$value)
        {
            
$value=$column->typecast($value);
            if(
is_string($value))
                
$value=$db->quoteValue($value);
        }
        if(
$n===1)
            return 
$prefix.$column->rawName.($values[0]===null?' IS NULL':'='.$values[0]);
        else
            return 
$prefix.$column->rawName.' IN ('.implode(', ',$values).')';
    }
    elseif(
is_array($columnName)) // composite key: $values=array(array('pk1'=>'v1','pk2'=>'v2'),array(...))
    
{
        foreach(
$columnName as $name)
        {
            if(!isset(
$table->columns[$name]))
                throw new 
CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
                array(
'{table}'=>$table->name'{column}'=>$name)));

            for(
$i=0;$i<$n;++$i)
            {
                if(isset(
$values[$i][$name]))
                {
                    
$value=$table->columns[$name]->typecast($values[$i][$name]);
                    if(
is_string($value))
                        
$values[$i][$name]=$db->quoteValue($value);
                    else
                        
$values[$i][$name]=$value;
                }
                else
                    throw new 
CDbException(Yii::t('yii','The value for the column "{column}" is not supplied when querying the table "{table}".',
                        array(
'{table}'=>$table->name,'{column}'=>$name)));
            }
        }
        if(
count($values)===1)
        {
            
$entries=array();
            foreach(
$values[0] as $name=>$value)
                
$entries[]=$prefix.$table->columns[$name]->rawName.($value===null?' IS NULL':'='.$value);
            return 
implode(' AND ',$entries);
        }

        return 
$this->createCompositeInCondition($table,$values,$prefix);
    }
    else
        throw new 
CDbException(Yii::t('yii','Column name must be either a string or an array.'));
}

Generates the expression for selecting rows of specified primary key values.

createInsertCommand() 方法
public CDbCommand createInsertCommand(mixed $table, array $data)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$data array data to be inserted (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
{return} CDbCommand insert command
源码: framework/db/schema/CDbCommandBuilder.php#208 (显示)
public function createInsertCommand($table,$data)
{
    
$this->ensureTable($table);
    
$fields=array();
    
$values=array();
    
$placeholders=array();
    
$i=0;
    foreach(
$data as $name=>$value)
    {
        if((
$column=$table->getColumn($name))!==null && ($value!==null || $column->allowNull))
        {
            
$fields[]=$column->rawName;
            if(
$value instanceof CDbExpression)
            {
                
$placeholders[]=$value->expression;
                foreach(
$value->params as $n=>$v)
                    
$values[$n]=$v;
            }
            else
            {
                
$placeholders[]=self::PARAM_PREFIX.$i;
                
$values[self::PARAM_PREFIX.$i]=$column->typecast($value);
                
$i++;
            }
        }
    }
    if(
$fields===array())
    {
        
$pks=is_array($table->primaryKey) ? $table->primaryKey : array($table->primaryKey);
        foreach(
$pks as $pk)
        {
            
$fields[]=$table->getColumn($pk)->rawName;
            
$placeholders[]=$this->getIntegerPrimaryKeyDefaultValue();
        }
    }
    
$sql="INSERT INTO {$table->rawName} (".implode(', ',$fields).') VALUES ('.implode(', ',$placeholders).')';
    
$command=$this->_connection->createCommand($sql);

    foreach(
$values as $name=>$value)
        
$command->bindValue($name,$value);

    return 
$command;
}

Creates an INSERT command.

createMultipleInsertCommand() 方法 (自版本 v1.1.14 可用)
public CDbCommand createMultipleInsertCommand(mixed $table, array $data)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$data array list data to be inserted, each value should be an array in format (column name=>column value). If a key is not a valid column name, the corresponding value will be ignored.
{return} CDbCommand multiple insert command
源码: framework/db/schema/CDbCommandBuilder.php#262 (显示)
public function createMultipleInsertCommand($table,array $data)
{
    return 
$this->composeMultipleInsertCommand($table,$data);
}

Creates a multiple INSERT command. This method could be used to achieve better performance during insertion of the large amount of data into the database tables.

createPkCondition() 方法
public string createPkCondition(mixed $table, array $values, string $prefix=NULL)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$values array list of primary key values to be selected within
$prefix string column prefix (ended with dot). If null, it will be the table name
{return} string the expression for selection
源码: framework/db/schema/CDbCommandBuilder.php#640 (显示)
public function createPkCondition($table,$values,$prefix=null)
{
    
$this->ensureTable($table);
    return 
$this->createInCondition($table,$table->primaryKey,$values,$prefix);
}

Generates the expression for selecting rows of specified primary key values.

createPkCriteria() 方法
public CDbCriteria createPkCriteria(mixed $table, mixed $pk, mixed $condition='', array $params=array ( ), string $prefix=NULL)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$pk mixed primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
$condition mixed query condition or criteria. If a string, it is treated as query condition; If an array, it is treated as the initial values for constructing a CDbCriteria; Otherwise, it should be an instance of CDbCriteria.
$params array parameters to be bound to an SQL statement. This is only used when the second parameter is a string (query condition). In other cases, please use CDbCriteria::params to set parameters.
$prefix string column prefix (ended with dot). If null, it will be the table name
{return} CDbCriteria the created query criteria
源码: framework/db/schema/CDbCommandBuilder.php#614 (显示)
public function createPkCriteria($table,$pk,$condition='',$params=array(),$prefix=null)
{
    
$this->ensureTable($table);
    
$criteria=$this->createCriteria($condition,$params);
    if(
$criteria->alias!='')
        
$prefix=$this->_schema->quoteTableName($criteria->alias).'.';
    if(!
is_array($pk)) // single key
        
$pk=array($pk);
    if(
is_array($table->primaryKey) && !isset($pk[0]) && $pk!==array()) // single composite key
        
$pk=array($pk);
    
$condition=$this->createInCondition($table,$table->primaryKey,$pk,$prefix);
    if(
$criteria->condition!='')
        
$criteria->condition=$condition.' AND ('.$criteria->condition.')';
    else
        
$criteria->condition=$condition;

    return 
$criteria;
}

Creates a query criteria with the specified primary key.

createSearchCondition() 方法
public string createSearchCondition(mixed $table, array $columns, mixed $keywords, string $prefix=NULL, boolean $caseSensitive=true)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$columns array list of column names for potential search condition.
$keywords mixed search keywords. This can be either a string with space-separated keywords or an array of keywords.
$prefix string optional column prefix (with dot at the end). If null, the table name will be used as the prefix.
$caseSensitive boolean whether the search is case-sensitive. Defaults to true.
{return} string SQL search condition matching on a set of columns. An empty string is returned if either the column array or the keywords are empty.
源码: framework/db/schema/CDbCommandBuilder.php#724 (显示)
public function createSearchCondition($table,$columns,$keywords,$prefix=null,$caseSensitive=true)
{
    
$this->ensureTable($table);
    if(!
is_array($keywords))
        
$keywords=preg_split('/\s+/u',$keywords,-1,PREG_SPLIT_NO_EMPTY);
    if(empty(
$keywords))
        return 
'';
    if(
$prefix===null)
        
$prefix=$table->rawName.'.';
    
$conditions=array();
    foreach(
$columns as $name)
    {
        if((
$column=$table->getColumn($name))===null)
            throw new 
CDbException(Yii::t('yii','Table "{table}" does not have a column named "{column}".',
                array(
'{table}'=>$table->name,'{column}'=>$name)));
        
$condition=array();
        foreach(
$keywords as $keyword)
        {
            
$keyword='%'.strtr($keyword,array('%'=>'\%''_'=>'\_''\\'=>'\\\\')).'%';
            if(
$caseSensitive)
                
$condition[]=$prefix.$column->rawName.' LIKE '.$this->_connection->quoteValue($keyword);
            else
                
$condition[]='LOWER('.$prefix.$column->rawName.') LIKE LOWER('.$this->_connection->quoteValue($keyword).')';
        }
        
$conditions[]=implode(' AND ',$condition);
    }
    return 
'('.implode(' OR ',$conditions).')';
}

Generates the expression for searching the specified keywords within a list of columns. The search expression is generated using the 'LIKE' SQL syntax. Every word in the keywords must be present and appear in at least one of the columns.

createSqlCommand() 方法
public CDbCommand createSqlCommand(string $sql, array $params=array ( ))
$sql string the explicitly specified SQL statement
$params array parameters that will be bound to the SQL statement
{return} CDbCommand the created command
源码: framework/db/schema/CDbCommandBuilder.php#454 (显示)
public function createSqlCommand($sql,$params=array())
{
    
$command=$this->_connection->createCommand($sql);
    
$this->bindValues($command,$params);
    return 
$command;
}

Creates a command based on a given SQL statement.

createUpdateCommand() 方法
public CDbCommand createUpdateCommand(mixed $table, array $data, CDbCriteria $criteria)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$data array list of columns to be updated (name=>value)
$criteria CDbCriteria the query criteria
{return} CDbCommand update command.
源码: framework/db/schema/CDbCommandBuilder.php#364 (显示)
public function createUpdateCommand($table,$data,$criteria)
{
    
$this->ensureTable($table);
    
$fields=array();
    
$values=array();
    
$bindByPosition=isset($criteria->params[0]);
    
$i=0;
    foreach(
$data as $name=>$value)
    {
        if((
$column=$table->getColumn($name))!==null)
        {
            if(
$value instanceof CDbExpression)
            {
                
$fields[]=$column->rawName.'='.$value->expression;
                foreach(
$value->params as $n=>$v)
                    
$values[$n]=$v;
            }
            elseif(
$bindByPosition)
            {
                
$fields[]=$column->rawName.'=?';
                
$values[]=$column->typecast($value);
            }
            else
            {
                
$fields[]=$column->rawName.'='.self::PARAM_PREFIX.$i;
                
$values[self::PARAM_PREFIX.$i]=$column->typecast($value);
                
$i++;
            }
        }
    }
    if(
$fields===array())
        throw new 
CDbException(Yii::t('yii','No columns are being updated for table "{table}".',
            array(
'{table}'=>$table->name)));
    
$sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
    
$sql=$this->applyJoin($sql,$criteria->join);
    
$sql=$this->applyCondition($sql,$criteria->condition);
    
$sql=$this->applyOrder($sql,$criteria->order);
    
$sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);

    
$command=$this->_connection->createCommand($sql);
    
$this->bindValues($command,array_merge($values,$criteria->params));

    return 
$command;
}

Creates an UPDATE command.

createUpdateCounterCommand() 方法
public CDbCommand createUpdateCounterCommand(mixed $table, array $counters, CDbCriteria $criteria)
$table mixed the table schema (CDbTableSchema) or the table name (string).
$counters array counters to be updated (counter increments/decrements indexed by column names.)
$criteria CDbCriteria the query criteria
{return} CDbCommand the created command
源码: framework/db/schema/CDbCommandBuilder.php#417 (显示)
public function createUpdateCounterCommand($table,$counters,$criteria)
{
    
$this->ensureTable($table);
    
$fields=array();
    foreach(
$counters as $name=>$value)
    {
        if((
$column=$table->getColumn($name))!==null)
        {
            
$value=(float)$value;
            if(
$value<0)
                
$fields[]="{$column->rawName}={$column->rawName}-".(-$value);
            else
                
$fields[]="{$column->rawName}={$column->rawName}+".$value;
        }
    }
    if(
$fields!==array())
    {
        
$sql="UPDATE {$table->rawName} SET ".implode(', ',$fields);
        
$sql=$this->applyJoin($sql,$criteria->join);
        
$sql=$this->applyCondition($sql,$criteria->condition);
        
$sql=$this->applyOrder($sql,$criteria->order);
        
$sql=$this->applyLimit($sql,$criteria->limit,$criteria->offset);
        
$command=$this->_connection->createCommand($sql);
        
$this->bindValues($command,$criteria->params);
        return 
$command;
    }
    else
        throw new 
CDbException(Yii::t('yii','No counter columns are being updated for table "{table}".',
            array(
'{table}'=>$table->name)));
}

Creates an UPDATE command that increments/decrements certain columns.

ensureTable() 方法
protected void ensureTable(mixed &$table)
$table mixed table schema (CDbTableSchema) or table name (string). If this refers to a valid table name, this parameter will be returned with the corresponding table schema.
源码: framework/db/schema/CDbCommandBuilder.php#859 (显示)
protected function ensureTable(&$table)
{
    if(
is_string($table) && ($table=$this->_schema->getTable($tableName=$table))===null)
        throw new 
CDbException(Yii::t('yii','Table "{table}" does not exist.',
            array(
'{table}'=>$tableName)));
}

Checks if the parameter is a valid table schema. If it is a string, the corresponding table schema will be retrieved.

getDbConnection() 方法
public CDbConnection getDbConnection()
{return} CDbConnection database connection.
源码: framework/db/schema/CDbCommandBuilder.php#40 (显示)
public function getDbConnection()
{
    return 
$this->_connection;
}

getIntegerPrimaryKeyDefaultValue() 方法 (自版本 v1.1.14 可用)
protected string getIntegerPrimaryKeyDefaultValue()
{return} string default value of the integer/serial primary key.
源码: framework/db/schema/CDbCommandBuilder.php#872 (显示)
protected function getIntegerPrimaryKeyDefaultValue()
{
    return 
'NULL';
}

Returns default value of the integer/serial primary key. Default value means that the next autoincrement/sequence value would be used.

getLastInsertID() 方法
public mixed getLastInsertID(mixed $table)
$table mixed the table schema (CDbTableSchema) or the table name (string).
{return} mixed last insertion id. Null is returned if no sequence name.
源码: framework/db/schema/CDbCommandBuilder.php#58 (显示)
public function getLastInsertID($table)
{
    
$this->ensureTable($table);
    if(
$table->sequenceName!==null)
        return 
$this->_connection->getLastInsertID($table->sequenceName);
    else
        return 
null;
}

Returns the last insertion ID for the specified table.

getSchema() 方法
public CDbSchema getSchema()
{return} CDbSchema the schema for this command builder.
源码: framework/db/schema/CDbCommandBuilder.php#48 (显示)
public function getSchema()
{
    return 
$this->_schema;
}