類別 yii\db\pgsql\QueryBuilder
繼承 | yii\db\pgsql\QueryBuilder » yii\db\QueryBuilder » yii\base\BaseObject |
---|---|
實作 | yii\base\Configurable |
自版本起可用 | 2.0 |
原始碼 | https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php |
QueryBuilder 是 PostgreSQL 資料庫的查詢建構器。
公開屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$conditionBuilders | array | 查詢條件到建構方法的映射。 | yii\db\QueryBuilder |
$conditionClasses | array | 條件別名到條件類別的映射。 | yii\db\QueryBuilder |
$db | yii\db\Connection | 資料庫連線。 | yii\db\QueryBuilder |
$expressionBuilders | string[]|yii\db\ExpressionBuilderInterface[] | 將表達式類別對應到表達式建立器類別。 | yii\db\QueryBuilder |
$separator | string (字串) | SQL 語句不同片段之間的分隔符。 | yii\db\QueryBuilder |
$typeMap | array | 從抽象的資料行類型(鍵)到實體的資料行類型(值)的對應。 | yii\db\pgsql\QueryBuilder |
公有方法
受保護的方法
方法 | 描述 | 定義於 |
---|---|---|
defaultConditionClasses() | 包含預設條件類別的陣列。如果您想要變更查詢建立器的預設條件類別,請擴充此方法。請參閱 $conditionClasses 文件以瞭解詳細資訊。 | yii\db\pgsql\QueryBuilder |
defaultExpressionBuilders() | 包含預設表達式建立器的陣列。如果您想要變更此查詢建立器的預設表達式建立器,請擴充並覆寫此方法。請參閱 $expressionBuilders 文件以瞭解詳細資訊。 | yii\db\pgsql\QueryBuilder |
extractAlias() | 擷取表格別名(如果有的話),否則傳回 false | yii\db\QueryBuilder |
hasLimit() | 檢查給定的 limit 是否有效。 | yii\db\QueryBuilder |
hasOffset() | 檢查給定的 offset 是否有效。 | yii\db\QueryBuilder |
prepareInsertSelectSubQuery() | 為 INSERT INTO ... SELECT SQL 語句準備 select 子查詢和欄位名稱。 | yii\db\QueryBuilder |
prepareInsertValues() | 為 INSERT SQL 語句準備 VALUES 部分。 |
yii\db\QueryBuilder |
prepareUpdateSets() | 為 UPDATE SQL 語句準備 SET 部分。 |
yii\db\QueryBuilder |
prepareUpsertColumns() | yii\db\QueryBuilder |
常數
常數 | 值 | 描述 | 定義於 |
---|---|---|---|
INDEX_B_TREE | 'btree' | 為 createIndex() 定義 B 樹索引。 | yii\db\pgsql\QueryBuilder |
INDEX_GIN | 'gin' | 為 createIndex() 定義 GIN 索引。 | yii\db\pgsql\QueryBuilder |
INDEX_GIST | 'gist' | 為 createIndex() 定義 GiST 索引。 | yii\db\pgsql\QueryBuilder |
INDEX_HASH | 'hash' | 為 createIndex() 定義雜湊索引。 | yii\db\pgsql\QueryBuilder |
INDEX_UNIQUE | 'unique' | 為 createIndex() 定義 UNIQUE 索引。 | yii\db\pgsql\QueryBuilder |
PARAM_PREFIX | ':qp' | 自動產生的查詢繫結參數的前綴。 | yii\db\QueryBuilder |
屬性詳細資訊
從抽象的資料行類型(鍵)到實體的資料行類型(值)的對應。
\yii\db\pgsql\Schema::TYPE_PK => 'serial NOT NULL PRIMARY KEY',
\yii\db\pgsql\Schema::TYPE_UPK => 'serial NOT NULL PRIMARY KEY',
\yii\db\pgsql\Schema::TYPE_BIGPK => 'bigserial NOT NULL PRIMARY KEY',
\yii\db\pgsql\Schema::TYPE_UBIGPK => 'bigserial NOT NULL PRIMARY KEY',
\yii\db\pgsql\Schema::TYPE_CHAR => 'char(1)',
\yii\db\pgsql\Schema::TYPE_STRING => 'varchar(255)',
\yii\db\pgsql\Schema::TYPE_TEXT => 'text',
\yii\db\pgsql\Schema::TYPE_TINYINT => 'smallint',
\yii\db\pgsql\Schema::TYPE_SMALLINT => 'smallint',
\yii\db\pgsql\Schema::TYPE_INTEGER => 'integer',
\yii\db\pgsql\Schema::TYPE_BIGINT => 'bigint',
\yii\db\pgsql\Schema::TYPE_FLOAT => 'double precision',
\yii\db\pgsql\Schema::TYPE_DOUBLE => 'double precision',
\yii\db\pgsql\Schema::TYPE_DECIMAL => 'numeric(10,0)',
\yii\db\pgsql\Schema::TYPE_DATETIME => 'timestamp(0)',
\yii\db\pgsql\Schema::TYPE_TIMESTAMP => 'timestamp(0)',
\yii\db\pgsql\Schema::TYPE_TIME => 'time(0)',
\yii\db\pgsql\Schema::TYPE_DATE => 'date',
\yii\db\pgsql\Schema::TYPE_BINARY => 'bytea',
\yii\db\pgsql\Schema::TYPE_BOOLEAN => 'boolean',
\yii\db\pgsql\Schema::TYPE_MONEY => 'numeric(19,4)',
\yii\db\pgsql\Schema::TYPE_JSON => 'jsonb',
]
方法詳細資訊
public mixed __call ( $name, $params ) | ||
$name | string (字串) |
方法名稱 |
$params | array |
方法參數 |
return (傳回) | mixed (混合型) |
方法傳回值 |
---|---|---|
throws (拋出) | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
定義於: yii\db\QueryBuilder::__construct()
建構子。
public void __construct ( $connection, $config = [] ) | ||
$connection (連線) | yii\db\Connection |
資料庫連線。 |
$config (設定) | array |
將用於初始化物件屬性的名稱-值配對 |
public function __construct($connection, $config = [])
{
$this->db = $connection;
parent::__construct($config);
}
定義於: yii\base\BaseObject::__get()
傳回物件屬性的值。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $object->property;
時,它會被隱式呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string (字串) |
屬性名稱 |
return (傳回) | mixed (混合型) |
屬性值 |
---|---|---|
throws (拋出) | yii\base\UnknownPropertyException |
如果屬性未定義 |
throws (拋出) | yii\base\InvalidCallException |
如果屬性為唯寫 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter();
} elseif (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\BaseObject::__isset()
檢查屬性是否已設定,亦即已定義且非 null。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($object->property)
時,它會被隱式呼叫。
請注意,如果屬性未定義,將傳回 false。
public boolean __isset ( $name ) | ||
$name | string (字串) |
屬性名稱或事件名稱 |
return (傳回) | boolean (布林值) |
具名屬性是否已設定(非 null)。 |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
return false;
}
定義於: yii\base\BaseObject::__set()
設定物件屬性的值。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $object->property = $value;
時,它會被隱式呼叫。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string (字串) |
屬性名稱或事件名稱 |
$value (值) | mixed (混合型) |
屬性值 |
throws (拋出) | yii\base\UnknownPropertyException |
如果屬性未定義 |
---|---|---|
throws (拋出) | yii\base\InvalidCallException |
如果屬性為唯讀 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter($value);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
} else {
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
}
定義於: yii\base\BaseObject::__unset()
將物件屬性設為 null。
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($object->property)
時,它會被隱式呼叫。
請注意,如果屬性未定義,此方法將不會執行任何動作。如果屬性為唯讀,它將拋出例外。
public void __unset ( $name ) | ||
$name | string (字串) |
屬性名稱 |
throws (拋出) | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
} elseif (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
}
}
定義於: yii\db\QueryBuilder::addCheck()
建立 SQL 命令,用於為現有表格新增檢查約束。
public string addCheck ( $name, $table, $expression ) | ||
$name | string (字串) |
檢查約束的名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
將新增檢查約束的表格。名稱將由方法正確地加上引號。 |
$expression (表達式) | string (字串) |
|
return (傳回) | string (字串) |
用於為現有表格新增檢查約束的 SQL 語句。 |
---|
public function addCheck($name, $table, $expression)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' CHECK (' . $this->db->quoteSql($expression) . ')';
}
定義於: yii\db\QueryBuilder::addColumn()
建立 SQL 語句,用於新增資料庫資料行。
public string addColumn ( $table, $column, $type ) | ||
$table (表格) | string (字串) |
將新增資料行的新表格。表格名稱將由方法正確地加上引號。 |
$column (資料行) | string (字串) |
新資料行的名稱。名稱將由方法正確地加上引號。 |
$type (類型) | string (字串) |
資料行類型。getColumnType() 方法將被調用,以將抽象資料行類型(如果有的話)轉換為實體類型。任何未被識別為抽象類型的內容都將保留在產生的 SQL 中。例如,'string' 將被轉換為 'varchar(255)',而 'string not null' 將變成 'varchar(255) not null'。 |
return (傳回) | string (字串) |
用於新增資料行的 SQL 語句。 |
---|
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
定義於: yii\db\QueryBuilder::addCommentOnColumn()
建立 SQL 命令,用於為資料行新增註解。
public string addCommentOnColumn ( $table, $column, $comment ) | ||
$table (表格) | string (字串) |
要註解其資料行的表格。表格名稱將由方法正確地加上引號。 |
$column (資料行) | string (字串) |
要註解的資料行名稱。資料行名稱將由方法正確地加上引號。 |
$comment (註解) | string (字串) |
要加入的註解文字。 註解將會被方法正確地引用。 |
return (傳回) | string (字串) |
用於在資料行上加入註解的 SQL 語句 |
---|
public function addCommentOnColumn($table, $column, $comment)
{
return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS ' . $this->db->quoteValue($comment);
}
定義於: yii\db\QueryBuilder::addCommentOnTable()
建立 SQL 命令,用於為表格新增註解。
public string addCommentOnTable ( $table, $comment ) | ||
$table (表格) | string (字串) |
要註解其資料行的表格。表格名稱將由方法正確地加上引號。 |
$comment (註解) | string (字串) |
要加入的註解文字。 註解將會被方法正確地引用。 |
return (傳回) | string (字串) |
用於在資料表上加入註解的 SQL 語句 |
---|
public function addCommentOnTable($table, $comment)
{
return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS ' . $this->db->quoteValue($comment);
}
定義於: yii\db\QueryBuilder::addDefaultValue()
建立 SQL 命令,用於為現有表格新增預設值約束。
public string addDefaultValue ( $name, $table, $column, $value ) | ||
$name | string (字串) |
預設值約束的名稱。 名稱將會被方法正確地引用。 |
$table (表格) | string (字串) |
將要加入預設值約束的資料表。 名稱將會被方法正確地引用。 |
$column (資料行) | string (字串) |
將要加入約束的資料行名稱。 名稱將會被方法正確地引用。 |
$value (值) | mixed (混合型) |
預設值。 |
return (傳回) | string (字串) |
用於將預設值約束加入到現有資料表的 SQL 語句。 |
---|---|---|
throws (拋出) | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能。 |
public function addDefaultValue($name, $table, $column, $value)
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
}
public string addForeignKey ( $name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null ) | ||
$name | string (字串) |
外鍵約束的名稱。 |
$table (表格) | string (字串) |
將要加入外鍵約束的資料表。 |
$columns | string|array |
將要加入約束的資料行名稱。 如果有多個資料行,請用逗號分隔或使用陣列來表示。 |
$refTable | string (字串) |
外鍵參考的資料表。 |
$refColumns | string|array |
外鍵參考的資料行名稱。 如果有多個資料行,請用逗號分隔或使用陣列來表示。 |
$delete | string|null |
ON DELETE 選項。 大多數 DBMS 支援這些選項:RESTRICT、CASCADE、NO ACTION、SET DEFAULT、SET NULL |
$update | string|null |
ON UPDATE 選項。 大多數 DBMS 支援這些選項:RESTRICT、CASCADE、NO ACTION、SET DEFAULT、SET NULL |
return (傳回) | string (字串) |
用於將外鍵約束加入到現有資料表的 SQL 語句。 |
---|
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$sql = 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD CONSTRAINT ' . $this->db->quoteColumnName($name)
. ' FOREIGN KEY (' . $this->buildColumns($columns) . ')'
. ' REFERENCES ' . $this->db->quoteTableName($refTable)
. ' (' . $this->buildColumns($refColumns) . ')';
if ($delete !== null) {
$sql .= ' ON DELETE ' . $delete;
}
if ($update !== null) {
$sql .= ' ON UPDATE ' . $update;
}
return $sql;
}
定義於: yii\db\QueryBuilder::addPrimaryKey()
建立 SQL 語句,用於為現有表格新增主鍵約束。
public string addPrimaryKey ( $name, $table, $columns ) | ||
$name | string (字串) |
主鍵約束的名稱。 |
$table (表格) | string (字串) |
將要加入主鍵約束的資料表。 |
$columns | string|array |
主鍵將包含的資料行,以逗號分隔的字串或陣列。 |
return (傳回) | string (字串) |
用於將主鍵約束加入到現有資料表的 SQL 語句。 |
---|
public function addPrimaryKey($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' PRIMARY KEY ('
. implode(', ', $columns) . ')';
}
定義於: yii\db\QueryBuilder::addUnique()
建立 SQL 命令,用於為現有表格新增唯一性約束。
public string addUnique ( $name, $table, $columns ) | ||
$name | string (字串) |
唯一性約束的名稱。 名稱將會被方法正確地引用。 |
$table (表格) | string (字串) |
將要加入唯一性約束的資料表。 名稱將會被方法正確地引用。 |
$columns | string|array |
將要加入約束的資料行名稱。 如果有多個資料行,請用逗號分隔。 名稱將會被方法正確地引用。 |
return (傳回) | string (字串) |
用於將唯一性約束加入到現有資料表的 SQL 語句。 |
---|
public function addUnique($name, $table, $columns)
{
if (is_string($columns)) {
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($columns as $i => $col) {
$columns[$i] = $this->db->quoteColumnName($col);
}
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' ADD CONSTRAINT '
. $this->db->quoteColumnName($name) . ' UNIQUE ('
. implode(', ', $columns) . ')';
}
建立 SQL 語句,用於變更資料行的定義。
public string alterColumn ( $table, $column, $type ) | ||
$table (表格) | string (字串) |
要變更資料行的資料表。 資料表名稱將會被方法正確地引用。 |
$column (資料行) | string (字串) |
要變更的資料行名稱。 名稱將會被方法正確地引用。 |
$type (類型) | string (字串) |
新的資料行類型。 將會呼叫 getColumnType() 方法來將抽象資料行類型(如果有的話)轉換為實體類型。 任何未被識別為抽象類型的內容都將保留在產生的 SQL 中。 例如,'string' 將會變成 'varchar(255)',而 'string not null' 將會變成 'varchar(255) not null'。 您也可以使用 PostgreSQL 特定的語法,例如 |
return (傳回) | string (字串) |
用於變更資料行定義的 SQL 語句。 |
---|
public function alterColumn($table, $column, $type)
{
$columnName = $this->db->quoteColumnName($column);
$tableName = $this->db->quoteTableName($table);
// https://github.com/yiisoft/yii2/issues/4492
// https://postgresql.dev.org.tw/docs/9.1/sql-altertable.html
if (preg_match('/^(DROP|SET|RESET)\s+/i', $type)) {
return "ALTER TABLE {$tableName} ALTER COLUMN {$columnName} {$type}";
}
$type = 'TYPE ' . $this->getColumnType($type);
$multiAlterStatement = [];
$constraintPrefix = preg_replace('/[^a-z0-9_]/i', '', $table . '_' . $column);
if (preg_match('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', $type, $matches)) {
$type = preg_replace('/\s+DEFAULT\s+(["\']?\w*["\']?)/i', '', $type);
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET DEFAULT {$matches[1]}";
} else {
// safe to drop default even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP DEFAULT";
}
$type = preg_replace('/\s+NOT\s+NULL/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ALTER COLUMN {$columnName} SET NOT NULL";
} else {
// remove additional null if any
$type = preg_replace('/\s+NULL/i', '', $type);
// safe to drop not null even if there was none in the first place
$multiAlterStatement[] = "ALTER COLUMN {$columnName} DROP NOT NULL";
}
if (preg_match('/\s+CHECK\s+\((.+)\)/i', $type, $matches)) {
$type = preg_replace('/\s+CHECK\s+\((.+)\)/i', '', $type);
$multiAlterStatement[] = "ADD CONSTRAINT {$constraintPrefix}_check CHECK ({$matches[1]})";
}
$type = preg_replace('/\s+UNIQUE/i', '', $type, -1, $count);
if ($count) {
$multiAlterStatement[] = "ADD UNIQUE ({$columnName})";
}
// add what's left at the beginning
array_unshift($multiAlterStatement, "ALTER COLUMN {$columnName} {$type}");
return 'ALTER TABLE ' . $tableName . ' ' . implode(', ', $multiAlterStatement);
}
產生批次 INSERT SQL 語句。
例如:
$sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
]);
請注意,每列中的值必須與對應的資料行名稱相符。
此方法將正確地跳脫資料行名稱,並引用要插入的值。
public string batchInsert ( $table, $columns, $rows, &$params = [] ) | ||
$table (表格) | string (字串) |
新列將要插入的資料表。 |
$columns | array |
資料行名稱 |
$rows | array|Generator |
要批次插入到資料表的列 |
$params | array |
繫結參數。 此參數自 2.0.14 版本起存在 |
return (傳回) | string (字串) |
批次 INSERT SQL 語句 |
---|
public function batchInsert($table, $columns, $rows, &$params = [])
{
if (empty($rows)) {
return '';
}
$schema = $this->db->getSchema();
if (($tableSchema = $schema->getTableSchema($table)) !== null) {
$columnSchemas = $tableSchema->columns;
} else {
$columnSchemas = [];
}
$values = [];
foreach ($rows as $row) {
$vs = [];
foreach ($row as $i => $value) {
if (isset($columns[$i], $columnSchemas[$columns[$i]])) {
$value = $columnSchemas[$columns[$i]]->dbTypecast($value);
}
if (is_string($value)) {
$value = $schema->quoteValue($value);
} elseif (is_float($value)) {
// ensure type cast always has . as decimal separator in all locales
$value = StringHelper::floatToString($value);
} elseif ($value === true) {
$value = 'TRUE';
} elseif ($value === false) {
$value = 'FALSE';
} elseif ($value === null) {
$value = 'NULL';
} elseif ($value instanceof ExpressionInterface) {
$value = $this->buildExpression($value, $params);
}
$vs[] = $value;
}
$values[] = '(' . implode(', ', $vs) . ')';
}
if (empty($values)) {
return '';
}
foreach ($columns as $i => $name) {
$columns[$i] = $schema->quoteColumnName($name);
}
return 'INSERT INTO ' . $schema->quoteTableName($table)
. ' (' . implode(', ', $columns) . ') VALUES ' . implode(', ', $values);
}
定義於: yii\db\QueryBuilder::bindParam()
輔助方法,使用 PARAM_PREFIX 將 $value 新增至 $params 陣列。
public string bindParam ( $value, &$params ) | ||
$value (值) | string|null | |
$params | array |
以參考方式傳遞 |
return (傳回) | string (字串) |
$params 陣列中的佔位符名稱 |
---|
public function bindParam($value, &$params)
{
$phName = self::PARAM_PREFIX . count($params);
$params[$phName] = $value;
return $phName;
}
定義於: yii\db\QueryBuilder::build()
從 yii\db\Query 物件產生 SELECT SQL 語句。
public array build ( $query, $params = [] ) | ||
$query | yii\db\Query |
將從中產生 SQL 語句的 yii\db\Query 物件。 |
$params | array |
要繫結到產生的 SQL 語句的參數。 這些參數將包含在結果中,以及在查詢建構過程中產生的其他參數。 |
return (傳回) | array |
產生的 SQL 語句(第一個陣列元素)和要繫結到 SQL 語句的對應參數(第二個陣列元素)。 傳回的參數包含 |
---|
public function build($query, $params = [])
{
$query = $query->prepare($this);
$params = empty($params) ? $query->params : array_merge($params, $query->params);
$clauses = [
$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption),
$this->buildFrom($query->from, $params),
$this->buildJoin($query->join, $params),
$this->buildWhere($query->where, $params),
$this->buildGroupBy($query->groupBy),
$this->buildHaving($query->having, $params),
];
$sql = implode($this->separator, array_filter($clauses));
$sql = $this->buildOrderByAndLimit($sql, $query->orderBy, $query->limit, $query->offset);
if (!empty($query->orderBy)) {
foreach ($query->orderBy as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
if (!empty($query->groupBy)) {
foreach ($query->groupBy as $expression) {
if ($expression instanceof ExpressionInterface) {
$this->buildExpression($expression, $params);
}
}
}
$union = $this->buildUnion($query->union, $params);
if ($union !== '') {
$sql = "($sql){$this->separator}$union";
}
$with = $this->buildWithQueries($query->withQueries, $params);
if ($with !== '') {
$sql = "$with{$this->separator}$sql";
}
return [$sql, $params];
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildAndCondition()
使用 AND
或 OR
運算子連接兩個或多個 SQL 表達式。
public string buildAndCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
用於連接給定運算元的運算符 |
$operands | array |
要連接的 SQL 表達式。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|
public function buildAndCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildBetweenCondition()
使用 BETWEEN
運算子建立 SQL 表達式。
public string buildBetweenCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
要使用的運算符(例如 |
$operands | array |
第一個運算元是資料行名稱。 第二個和第三個運算元描述了資料行值應在的間隔。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果給定的運算元數量錯誤。 |
public function buildBetweenCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildColumns ( $columns ) | ||
$columns | string|array |
要處理的資料行 |
return (傳回) | string (字串) |
處理結果 |
---|
public function buildColumns($columns)
{
if (!is_array($columns)) {
if (strpos($columns, '(') !== false) {
return $columns;
}
$rawColumns = $columns;
$columns = preg_split('/\s*,\s*/', $columns, -1, PREG_SPLIT_NO_EMPTY);
if ($columns === false) {
throw new InvalidArgumentException("$rawColumns is not valid columns.");
}
}
foreach ($columns as $i => $column) {
if ($column instanceof ExpressionInterface) {
$columns[$i] = $this->buildExpression($column);
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return implode(', ', $columns);
}
定義於: yii\db\QueryBuilder::buildCondition()
解析條件規格,並產生對應的 SQL 表達式。
public string buildCondition ( $condition, &$params ) | ||
$condition | string|array|yii\db\ExpressionInterface |
條件規格。 請參考 yii\db\Query::where(),了解如何指定條件。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|
public function buildCondition($condition, &$params)
{
if (is_array($condition)) {
if (empty($condition)) {
return '';
}
$condition = $this->createConditionFromArray($condition);
}
if ($condition instanceof ExpressionInterface) {
return $this->buildExpression($condition, $params);
}
return (string)$condition;
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildExistsCondition()
使用 EXISTS
運算子建立 SQL 表達式。
public string buildExistsCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
要使用的運算符(例如 |
$operands | array |
僅包含一個元素,即代表子查詢的 yii\db\Query 物件。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果運算元不是 yii\db\Query 物件。 |
public function buildExistsCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildExpression ( yii\db\ExpressionInterface $expression, &$params = [] ) | ||
$expression (表達式) | yii\db\ExpressionInterface |
要建構的表達式 |
$params | array |
要繫結到產生的 SQL 語句的參數。 這些參數將包含在結果中,以及在表達式建構過程中產生的其他參數。 |
return (傳回) | string (字串) |
在傳遞到 DBMS 之前,既不會被引用也不會被編碼的 SQL 語句 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
當此 QueryBuilder 不支援 $expression 建構時。 |
public function buildExpression(ExpressionInterface $expression, &$params = [])
{
$builder = $this->getExpressionBuilder($expression);
return $builder->build($expression, $params);
}
public string buildFrom ( $tables, &$params ) | ||
$tables | array | |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
從 yii\db\Query::$from 建構的 FROM 子句。 |
---|
public function buildFrom($tables, &$params)
{
if (empty($tables)) {
return '';
}
$tables = $this->quoteTableNames($tables, $params);
return 'FROM ' . implode(', ', $tables);
}
public string buildGroupBy ( $columns ) | ||
$columns | array | |
return (傳回) | string (字串) |
GROUP BY 子句 |
---|
public function buildGroupBy($columns)
{
if (empty($columns)) {
return '';
}
foreach ($columns as $i => $column) {
if ($column instanceof ExpressionInterface) {
$columns[$i] = $this->buildExpression($column);
} elseif (strpos($column, '(') === false) {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
return 'GROUP BY ' . implode(', ', $columns);
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildHashCondition()
根據資料行-值配對建立條件。
public string buildHashCondition ( $condition, &$params ) | ||
$condition | array |
條件規格。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|
public function buildHashCondition($condition, &$params)
{
return $this->buildCondition(new HashCondition($condition), $params);
}
public string buildHaving ( $condition, &$params ) | ||
$condition | string|array | |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
從 yii\db\Query::$having 建構的 HAVING 子句。 |
---|
public function buildHaving($condition, &$params)
{
$having = $this->buildCondition($condition, $params);
return $having === '' ? '' : 'HAVING ' . $having;
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildInCondition()
使用 IN
運算子建立 SQL 表達式。
public string buildInCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
要使用的運算符(例如 |
$operands | array |
第一個運算元是資料行名稱。 如果它是陣列,將會產生複合 IN 條件。 第二個運算元是一個值陣列,資料行值應該在其中。 如果它是空陣列,則如果運算符為 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\db\Exception |
如果給定的運算元數量錯誤。 |
public function buildInCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildJoin ( $joins, &$params ) | ||
$joins | array | |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
從 yii\db\Query::$join 建構的 JOIN 子句。 |
---|---|---|
throws (拋出) | yii\db\Exception |
如果 $joins 參數格式不正確 |
public function buildJoin($joins, &$params)
{
if (empty($joins)) {
return '';
}
foreach ($joins as $i => $join) {
if (!is_array($join) || !isset($join[0], $join[1])) {
throw new Exception('A join clause must be specified as an array of join type, join table, and optionally join condition.');
}
// 0:join type, 1:join table, 2:on-condition (optional)
list($joinType, $table) = $join;
$tables = $this->quoteTableNames((array)$table, $params);
$table = reset($tables);
$joins[$i] = "$joinType $table";
if (isset($join[2])) {
$condition = $this->buildCondition($join[2], $params);
if ($condition !== '') {
$joins[$i] .= ' ON ' . $condition;
}
}
}
return implode($this->separator, $joins);
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildLikeCondition()
使用 LIKE
運算子建立 SQL 表達式。
public string buildLikeCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
要使用的運算符(例如 |
$operands | array |
包含兩個或三個運算元的陣列
|
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果給定的運算元數量錯誤。 |
public function buildLikeCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildLimit ( $limit, $offset ) | ||
$limit | integer | |
$offset | integer | |
return (傳回) | string (字串) |
LIMIT 和 OFFSET 子句 |
---|
public function buildLimit($limit, $offset)
{
$sql = '';
if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
}
if ($this->hasOffset($offset)) {
$sql .= ' OFFSET ' . $offset;
}
return ltrim($sql);
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildNotCondition()
使用 NOT
運算子反轉 SQL 表達式。
public string buildNotCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
用於連接給定運算元的運算符 |
$operands | array |
要連接的 SQL 表達式。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果給定的運算元數量錯誤。 |
public function buildNotCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildOrderBy ( $columns ) | ||
$columns | array | |
return (傳回) | string (字串) |
從 yii\db\Query::$orderBy 建構的 ORDER BY 子句。 |
---|
public function buildOrderBy($columns)
{
if (empty($columns)) {
return '';
}
$orders = [];
foreach ($columns as $name => $direction) {
if ($direction instanceof ExpressionInterface) {
$orders[] = $this->buildExpression($direction);
} else {
$orders[] = $this->db->quoteColumnName($name) . ($direction === SORT_DESC ? ' DESC' : '');
}
}
return 'ORDER BY ' . implode(', ', $orders);
}
定義於: yii\db\QueryBuilder::buildOrderByAndLimit()
建立 ORDER BY 和 LIMIT/OFFSET 子句,並將它們附加到給定的 SQL。
public string buildOrderByAndLimit ( $sql, $orderBy, $limit, $offset ) | ||
$sql | string (字串) |
現有的 SQL (不含 ORDER BY/LIMIT/OFFSET) |
$orderBy | array |
排序依據的資料行。 有關如何指定此參數的更多詳細資訊,請參閱 yii\db\Query::orderBy()。 |
$limit | integer |
限制數量。 有關更多詳細資訊,請參閱 yii\db\Query::limit()。 |
$offset | integer |
偏移量。 有關更多詳細資訊,請參閱 yii\db\Query::offset()。 |
return (傳回) | string (字串) |
完成 ORDER BY/LIMIT/OFFSET 的 SQL (如果有的話) |
---|
public function buildOrderByAndLimit($sql, $orderBy, $limit, $offset)
{
$orderBy = $this->buildOrderBy($orderBy);
if ($orderBy !== '') {
$sql .= $this->separator . $orderBy;
}
$limit = $this->buildLimit($limit, $offset);
if ($limit !== '') {
$sql .= $this->separator . $limit;
}
return $sql;
}
public string buildSelect ( $columns, &$params, $distinct = false, $selectOption = null ) | ||
$columns | array | |
$params | array |
要填入的繫結參數 |
$distinct | boolean (布林值) | |
$selectOption | string|null | |
return (傳回) | string (字串) |
從 yii\db\Query::$select 建構的 SELECT 子句。 |
---|
public function buildSelect($columns, &$params, $distinct = false, $selectOption = null)
{
$select = $distinct ? 'SELECT DISTINCT' : 'SELECT';
if ($selectOption !== null) {
$select .= ' ' . $selectOption;
}
if (empty($columns)) {
return $select . ' *';
}
foreach ($columns as $i => $column) {
if ($column instanceof ExpressionInterface) {
if (is_int($i)) {
$columns[$i] = $this->buildExpression($column, $params);
} else {
$columns[$i] = $this->buildExpression($column, $params) . ' AS ' . $this->db->quoteColumnName($i);
}
} elseif ($column instanceof Query) {
list($sql, $params) = $this->build($column, $params);
$columns[$i] = "($sql) AS " . $this->db->quoteColumnName($i);
} elseif (is_string($i) && $i !== $column) {
if (strpos($column, '(') === false) {
$column = $this->db->quoteColumnName($column);
}
$columns[$i] = "$column AS " . $this->db->quoteColumnName($i);
} elseif (strpos($column, '(') === false) {
if (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $column, $matches)) {
$columns[$i] = $this->db->quoteColumnName($matches[1]) . ' AS ' . $this->db->quoteColumnName($matches[2]);
} else {
$columns[$i] = $this->db->quoteColumnName($column);
}
}
}
return $select . ' ' . implode(', ', $columns);
}
buildCondition()
。
定義於: yii\db\QueryBuilder::buildSimpleCondition()
建立類似 "column" operator value
的 SQL 表達式。
public string buildSimpleCondition ( $operator, $operands, &$params ) | ||
$operator | string (字串) |
要使用的運算子。可以使用任何符號,例如 |
$operands | array |
包含兩個欄位名稱。 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
產生的 SQL 表達式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果給定的運算元數量錯誤。 |
public function buildSimpleCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildUnion ( $unions, &$params ) | ||
$unions | array | |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
從 yii\db\Query::$union 建構的 UNION 子句。 |
---|
public function buildUnion($unions, &$params)
{
if (empty($unions)) {
return '';
}
$result = '';
foreach ($unions as $i => $union) {
$query = $union['query'];
if ($query instanceof Query) {
list($unions[$i]['query'], $params) = $this->build($query, $params);
}
$result .= 'UNION ' . ($union['all'] ? 'ALL ' : '') . '( ' . $unions[$i]['query'] . ' ) ';
}
return trim($result);
}
public string buildWhere ( $condition, &$params ) | ||
$condition | string|array | |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
從 yii\db\Query::$where 建構的 WHERE 子句。 |
---|
public function buildWhere($condition, &$params)
{
$where = $this->buildCondition($condition, $params);
return $where === '' ? '' : 'WHERE ' . $where;
}
public string buildWithQueries ( $withs, &$params ) | ||
$withs | array |
每個 WITH 查詢的組態 |
$params | array |
要填入的繫結參數 |
return (傳回) | string (字串) |
編譯後的 WITH 查詢前綴,包含巢狀查詢 |
---|
public function buildWithQueries($withs, &$params)
{
if (empty($withs)) {
return '';
}
$recursive = false;
$result = [];
foreach ($withs as $i => $with) {
if ($with['recursive']) {
$recursive = true;
}
$query = $with['query'];
if ($query instanceof Query) {
list($with['query'], $params) = $this->build($query, $params);
}
$result[] = $with['alias'] . ' AS (' . $with['query'] . ')';
}
return 'WITH ' . ($recursive ? 'RECURSIVE ' : '') . implode(', ', $result);
}
定義於: yii\base\BaseObject::canGetProperty()
傳回值,指示是否可以讀取屬性。
當屬性符合以下條件時為可讀:
- 類別具有與指定名稱相關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時);
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true ) | ||
$name | string (字串) |
屬性名稱 |
$checkVars | boolean (布林值) |
是否將成員變數視為屬性 |
return (傳回) | boolean (布林值) |
屬性是否可讀 |
---|
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
定義於: yii\base\BaseObject::canSetProperty()
傳回值,指示是否可以設定屬性。
當屬性符合以下條件時為可寫:
- 類別具有與指定名稱相關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時);
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true ) | ||
$name | string (字串) |
屬性名稱 |
$checkVars | boolean (布林值) |
是否將成員變數視為屬性 |
return (傳回) | boolean (布林值) |
屬性是否可寫 |
---|
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
建立 SQL 語句,用於啟用或停用完整性檢查。
public string checkIntegrity ( $check = true, $schema = '', $table = '' ) | ||
$check | boolean (布林值) |
是否開啟或關閉完整性檢查。 |
$schema | string (字串) |
表格的綱要。 |
$table (表格) | string (字串) |
表格名稱。 |
return (傳回) | string (字串) |
用於檢查完整性的 SQL 陳述式 |
---|
public function checkIntegrity($check = true, $schema = '', $table = '')
{
$enable = $check ? 'ENABLE' : 'DISABLE';
$schema = $schema ?: $this->db->getSchema()->defaultSchema;
$tableNames = $table ? [$table] : $this->db->getSchema()->getTableNames($schema);
$viewNames = $this->db->getSchema()->getViewNames($schema);
$tableNames = array_diff($tableNames, $viewNames);
$command = '';
foreach ($tableNames as $tableName) {
$tableName = $this->db->quoteTableName("{$schema}.{$tableName}");
$command .= "ALTER TABLE $tableName $enable TRIGGER ALL; ";
}
// enable to have ability to alter several tables
$this->db->getMasterPdo()->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
return $command;
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return (傳回) | string (字串) |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
定義於: yii\db\QueryBuilder::createConditionFromArray()
根據 $conditionClasses 對應,將以陣列格式定義的 $condition(如 yii\db\Query::where() 中所述)轉換為 yii\db\condition\ConditionInterface 的實例。
另請參閱 $conditionClasses。
public yii\db\conditions\ConditionInterface createConditionFromArray ( $condition ) | ||
$condition | string|array |
public function createConditionFromArray($condition)
{
if (isset($condition[0])) { // operator format: operator, operand 1, operand 2, ...
$operator = strtoupper(array_shift($condition));
if (isset($this->conditionClasses[$operator])) {
$className = $this->conditionClasses[$operator];
} else {
$className = 'yii\db\conditions\SimpleCondition';
}
/** @var ConditionInterface $className */
return $className::fromArrayDefinition($operator, $condition);
}
// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
return new HashCondition($condition);
}
建立 SQL 語句,用於建立新的索引。
另請參閱 https://postgresql.dev.org.tw/docs/8.2/sql-createindex.html。
public string createIndex ( $name, $table, $columns, $unique = false ) | ||
$name | string (字串) |
索引的名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
將在其上建立新索引的表格。表格名稱將由方法正確地加上引號。 |
$columns | string|array |
應包含在索引中的欄位。如果有多個欄位,請用逗號分隔或使用陣列表示。每個欄位名稱將由方法正確地加上引號,除非在名稱中找到括號。 |
$unique | boolean|string |
是否將此設為 UNIQUE 索引約束。您可以傳遞 |
return (傳回) | string (字串) |
用於建立新索引的 SQL 陳述式。 |
---|
public function createIndex($name, $table, $columns, $unique = false)
{
if ($unique === self::INDEX_UNIQUE || $unique === true) {
$index = false;
$unique = true;
} else {
$index = $unique;
$unique = false;
}
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ') .
$this->db->quoteTableName($name) . ' ON ' .
$this->db->quoteTableName($table) .
($index !== false ? " USING $index" : '') .
' (' . $this->buildColumns($columns) . ')';
}
定義於: yii\db\QueryBuilder::createTable()
建立 SQL 語句,用於建立新的資料庫表格。
新表格中的欄位應指定為名稱-定義配對(例如 'name' => 'string'),其中 name 代表欄位名稱,將由方法正確地加上引號,而 definition 代表欄位類型,必須包含抽象 DB 類型。getColumnType() 方法將被調用,以將任何抽象類型轉換為物理類型。
如果僅使用定義指定欄位(例如 'PRIMARY KEY (name, type)'),它將直接插入到產生的 SQL 中。
例如:
$sql = $queryBuilder->createTable('user', [
'id' => 'pk',
'name' => 'string',
'age' => 'integer',
'column_name double precision null default null', # definition only example
]);
public string createTable ( $table, $columns, $options = null ) | ||
$table (表格) | string (字串) |
要建立的表格名稱。名稱將由方法正確地加上引號。 |
$columns | array |
新表格中的欄位(名稱 => 定義)。 |
$options | string|null |
將附加到產生的 SQL 的其他 SQL 片段。 |
return (傳回) | string (字串) |
用於建立新 DB 表格的 SQL 陳述式。 |
---|
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;
}
定義於: yii\db\QueryBuilder::createView()
建立 SQL 視圖。
public string createView ( $viewName, $subQuery ) | ||
$viewName | string (字串) |
要建立的檢視表名稱。 |
$subQuery | string|yii\db\Query |
定義檢視表的 select 陳述式。這可以是字串或 yii\db\Query 物件。 |
return (傳回) | string (字串) |
|
---|
public function createView($viewName, $subQuery)
{
if ($subQuery instanceof Query) {
list($rawQuery, $params) = $this->build($subQuery);
array_walk(
$params,
function (&$param) {
$param = $this->db->quoteValue($param);
}
);
$subQuery = strtr($rawQuery, $params);
}
return 'CREATE VIEW ' . $this->db->quoteTableName($viewName) . ' AS ' . $subQuery;
}
包含預設條件類別的陣列。如果您想要變更查詢建立器的預設條件類別,請擴充此方法。請參閱 $conditionClasses 文件以瞭解詳細資訊。
protected array defaultConditionClasses ( ) |
protected function defaultConditionClasses()
{
return array_merge(parent::defaultConditionClasses(), [
'ILIKE' => 'yii\db\conditions\LikeCondition',
'NOT ILIKE' => 'yii\db\conditions\LikeCondition',
'OR ILIKE' => 'yii\db\conditions\LikeCondition',
'OR NOT ILIKE' => 'yii\db\conditions\LikeCondition',
]);
}
包含預設表達式建立器的陣列。如果您想要變更此查詢建立器的預設表達式建立器,請擴充並覆寫此方法。請參閱 $expressionBuilders 文件以瞭解詳細資訊。
protected array defaultExpressionBuilders ( ) |
protected function defaultExpressionBuilders()
{
return array_merge(parent::defaultExpressionBuilders(), [
'yii\db\ArrayExpression' => 'yii\db\pgsql\ArrayExpressionBuilder',
'yii\db\JsonExpression' => 'yii\db\pgsql\JsonExpressionBuilder',
]);
}
定義於: yii\db\QueryBuilder::delete()
建立 DELETE SQL 語句。
例如:
$sql = $queryBuilder->delete('user', 'status = 0');
此方法將正確地跳脫表格和欄位名稱。
public string delete ( $table, $condition, &$params ) | ||
$table (表格) | string (字串) |
將從中刪除資料的表格。 |
$condition | array|string |
將放在 WHERE 部分的條件。請參閱 yii\db\Query::where() 了解如何指定條件。 |
$params | array |
綁定參數將由此方法修改,以便稍後可以綁定到 DB 命令。 |
return (傳回) | string (字串) |
DELETE SQL |
---|
public function delete($table, $condition, &$params)
{
$sql = 'DELETE FROM ' . $this->db->quoteTableName($table);
$where = $this->buildWhere($condition, $params);
return $where === '' ? $sql : $sql . ' ' . $where;
}
定義於: yii\db\QueryBuilder::dropCheck()
建立 SQL 命令,用於刪除檢查約束。
public string dropCheck ( $name, $table ) | ||
$name | string (字串) |
要移除的檢查約束名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
要移除其檢查約束的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除檢查約束的 SQL 陳述式。 |
---|
public function dropCheck($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
定義於: yii\db\QueryBuilder::dropColumn()
建立 SQL 語句,用於刪除資料庫資料行。
public string dropColumn ( $table, $column ) | ||
$table (表格) | string (字串) |
要移除欄位的表格。名稱將由方法正確地加上引號。 |
$column (資料行) | string (字串) |
要移除的欄位名稱。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除 DB 欄位的 SQL 陳述式。 |
---|
public function dropColumn($table, $column)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP COLUMN ' . $this->db->quoteColumnName($column);
}
定義於: yii\db\QueryBuilder::dropCommentFromColumn()
建立 SQL 命令,用於為資料行新增註解。
public string dropCommentFromColumn ( $table, $column ) | ||
$table (表格) | string (字串) |
要註解其資料行的表格。表格名稱將由方法正確地加上引號。 |
$column (資料行) | string (字串) |
要註解的資料行名稱。資料行名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於在資料行上加入註解的 SQL 語句 |
---|
public function dropCommentFromColumn($table, $column)
{
return 'COMMENT ON COLUMN ' . $this->db->quoteTableName($table) . '.' . $this->db->quoteColumnName($column) . ' IS NULL';
}
定義於: yii\db\QueryBuilder::dropCommentFromTable()
建立 SQL 命令,用於為表格新增註解。
public string dropCommentFromTable ( $table ) | ||
$table (表格) | string (字串) |
要註解其資料行的表格。表格名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於在資料行上加入註解的 SQL 語句 |
---|
public function dropCommentFromTable($table)
{
return 'COMMENT ON TABLE ' . $this->db->quoteTableName($table) . ' IS NULL';
}
定義於: yii\db\QueryBuilder::dropDefaultValue()
建立 SQL 命令,用於刪除預設值約束。
public string dropDefaultValue ( $name, $table ) | ||
$name | string (字串) |
要移除的預設值約束名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
要移除其預設值約束的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除預設值約束的 SQL 陳述式。 |
---|---|---|
throws (拋出) | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能。 |
public function dropDefaultValue($name, $table)
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support dropping default value constraints.');
}
定義於: yii\db\QueryBuilder::dropForeignKey()
建立 SQL 語句,用於刪除外鍵約束。
public string dropForeignKey ( $name, $table ) | ||
$name | string (字串) |
要移除的外鍵約束名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
要移除其外鍵的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除外鍵約束的 SQL 陳述式。 |
---|
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
建立 SQL 語句,用於刪除索引。
public string dropIndex ( $name, $table ) | ||
$name | string (字串) |
要移除的索引名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
要移除其索引的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除索引的 SQL 陳述式。 |
---|
public function dropIndex($name, $table)
{
if (strpos($table, '.') !== false && strpos($name, '.') === false) {
if (strpos($table, '{{') !== false) {
$table = preg_replace('/\\{\\{(.*?)\\}\\}/', '\1', $table);
list($schema, $table) = explode('.', $table);
if (strpos($schema, '%') === false) {
$name = $schema . '.' . $name;
} else {
$name = '{{' . $schema . '.' . $name . '}}';
}
} else {
list($schema) = explode('.', $table);
$name = $schema . '.' . $name;
}
}
return 'DROP INDEX ' . $this->db->quoteTableName($name);
}
定義於: yii\db\QueryBuilder::dropPrimaryKey()
建立 SQL 語句,用於從現有表格中移除主鍵約束。
public string dropPrimaryKey ( $name, $table ) | ||
$name | string (字串) |
要移除的主鍵約束名稱。 |
$table (表格) | string (字串) |
將從中移除主鍵約束的表格。 |
return (傳回) | string (字串) |
用於從現有表格中移除主鍵約束的 SQL 陳述式。 |
---|
public function dropPrimaryKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
定義於: yii\db\QueryBuilder::dropTable()
建立 SQL 語句,用於刪除資料庫表格。
public string dropTable ( $table ) | ||
$table (表格) | string (字串) |
要移除的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除 DB 表格的 SQL 陳述式。 |
---|
public function dropTable($table)
{
return 'DROP TABLE ' . $this->db->quoteTableName($table);
}
定義於: yii\db\QueryBuilder::dropUnique()
建立 SQL 命令,用於刪除唯一性約束。
public string dropUnique ( $name, $table ) | ||
$name | string (字串) |
要移除的唯一約束名稱。名稱將由方法正確地加上引號。 |
$table (表格) | string (字串) |
要移除其唯一約束的表格。名稱將由方法正確地加上引號。 |
return (傳回) | string (字串) |
用於移除唯一約束的 SQL 陳述式。 |
---|
public function dropUnique($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
定義於: yii\db\QueryBuilder::dropView()
刪除 SQL 視圖。
public string dropView ( $viewName ) | ||
$viewName | string (字串) |
要移除的檢視表名稱。 |
return (傳回) | string (字串) |
|
---|
public function dropView($viewName)
{
return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
}
定義於: yii\db\QueryBuilder::executeResetSequence()
執行 SQL 語句,用於重設表格主鍵的序號值。
執行 execute 的原因是某些資料庫 (Oracle) 需要數個查詢才能完成此操作。序列將被重設,以便下一個插入的新資料列的主鍵將具有指定的值,或者現有最大值 +1。
public void executeResetSequence ( $table, $value = null ) | ||
$table (表格) | string (字串) |
要重設主鍵序列的表格名稱 |
$value (值) | array|string|null |
下一個插入的新資料列的主鍵值。如果未設定,則下一個新資料列的主鍵將具有現有最大值 +1。 |
throws (拋出) | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能 |
---|
public function executeResetSequence($table, $value = null)
{
$this->db->createCommand()->resetSequence($table, $value)->execute();
}
定義於: yii\db\QueryBuilder::extractAlias()
擷取表格別名(如果有的話),否則傳回 false
protected boolean|array extractAlias ( $table ) | ||
$table (表格) |
protected function extractAlias($table)
{
if (preg_match('/^(.*?)(?i:\s+as|)\s+([^ ]+)$/', $table, $matches)) {
return $matches;
}
return false;
}
定義於: yii\db\QueryBuilder::getColumnType()
將抽象的資料行類型轉換為實體的資料行類型。
轉換是使用 $typeMap 中指定的類型映射完成的。以下抽象欄位類型受到支援(使用 MySQL 作為範例來說明對應的實體類型)
pk
:自動遞增主鍵類型,將轉換為 "int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY"bigpk
:自動遞增主鍵類型,將轉換為 "bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY"upk
:無符號自動遞增主鍵類型,將轉換為 "int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY"char
:char 類型,將轉換為 "char(1)"string
:字串類型,將轉換為 "varchar(255)"text
:長字串類型,將轉換為 "text"smallint
:小整數類型,將轉換為 "smallint(6)"integer
:整數類型,將轉換為 "int(11)"bigint
:大整數類型,將轉換為 "bigint(20)"boolean
:布林類型,將轉換為 "tinyint(1)"float
:浮點數類型,將轉換為 "float"decimal
:十進位數字類型,將轉換為 "decimal"datetime
:日期時間類型,將轉換為 "datetime"timestamp
:時間戳記類型,將轉換為 "timestamp"time
:時間類型,將轉換為 "time"date
:日期類型,將轉換為 "date"money
:貨幣類型,將轉換為 "decimal(19,4)"binary
:二進制資料類型,將轉換為 "blob"
如果抽象類型包含兩個或更多個以空格分隔的部分(例如 "string NOT NULL"),則只會轉換第一部分,其餘部分將附加到轉換結果中。例如,'string NOT NULL' 會轉換為 'varchar(255) NOT NULL'。
對於某些抽象類型,您也可以透過在類型後面的圓括號中直接附加長度或精確度約束來指定。例如,string(32)
在 MySQL 資料庫上將轉換為 "varchar(32)"。如果底層 DBMS 不支援類型的這些約束,則會被忽略。
如果在 $typeMap 中找不到類型,它將會不經任何變更地傳回。
public string getColumnType ( $type ) | ||
$type (類型) | string|yii\db\ColumnSchemaBuilder |
抽象欄位類型 |
return (傳回) | string (字串) |
實體欄位類型。 |
---|
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;
}
定義於: yii\db\QueryBuilder::getExpressionBuilder()
取得適用於 $expression 的 yii\db\ExpressionBuilderInterface 物件。
使用 $expressionBuilders 陣列來尋找合適的 builder 類別。
另請參閱 $expressionBuilders。
public yii\db\ExpressionBuilderInterface getExpressionBuilder ( yii\db\ExpressionInterface $expression ) | ||
$expression (表達式) | yii\db\ExpressionInterface | |
throws (拋出) | yii\base\InvalidArgumentException |
當此 QueryBuilder 不支援 $expression 建構時。 |
---|
public function getExpressionBuilder(ExpressionInterface $expression)
{
$className = get_class($expression);
if (!isset($this->expressionBuilders[$className])) {
foreach (array_reverse($this->expressionBuilders) as $expressionClass => $builderClass) {
if (is_subclass_of($expression, $expressionClass)) {
$this->expressionBuilders[$className] = $builderClass;
break;
}
}
if (!isset($this->expressionBuilders[$className])) {
throw new InvalidArgumentException('Expression of class ' . $className . ' can not be built in ' . get_class($this));
}
}
if ($this->expressionBuilders[$className] === __CLASS__) {
return $this;
}
if (!is_object($this->expressionBuilders[$className])) {
$this->expressionBuilders[$className] = new $this->expressionBuilders[$className]($this);
}
return $this->expressionBuilders[$className];
}
定義於: yii\db\QueryBuilder::hasLimit()
檢查給定的 limit 是否有效。
protected boolean hasLimit ( $limit ) | ||
$limit | mixed (混合型) |
給定的 limit |
return (傳回) | boolean (布林值) |
limit 是否有效 |
---|
protected function hasLimit($limit)
{
return ($limit instanceof ExpressionInterface) || ctype_digit((string)$limit);
}
定義於: yii\base\BaseObject::hasMethod()
傳回值,指示是否已定義方法。
預設實作是對 php 函數 method_exists()
的呼叫。當您實作 php 魔術方法 __call()
時,您可以覆寫此方法。
public boolean hasMethod ( $name ) | ||
$name | string (字串) |
方法名稱 |
return (傳回) | boolean (布林值) |
方法是否已定義 |
---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
定義於: yii\db\QueryBuilder::hasOffset()
檢查給定的 offset 是否有效。
protected boolean hasOffset ( $offset ) | ||
$offset | mixed (混合型) |
給定的 offset |
return (傳回) | boolean (布林值) |
offset 是否有效 |
---|
protected function hasOffset($offset)
{
return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0';
}
定義於: yii\base\BaseObject::hasProperty()
傳回值,指示是否已定義屬性。
如果滿足以下條件,則定義了屬性
- 類別具有與指定名稱關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時);
另請參閱
public boolean hasProperty ( $name, $checkVars = true ) | ||
$name | string (字串) |
屬性名稱 |
$checkVars | boolean (布林值) |
是否將成員變數視為屬性 |
return (傳回) | boolean (布林值) |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true)
{
return $this->canGetProperty($name, $checkVars) || $this->canSetProperty($name, false);
}
public void init ( ) |
public function init()
{
parent::init();
$this->expressionBuilders = array_merge($this->defaultExpressionBuilders(), $this->expressionBuilders);
$this->conditionClasses = array_merge($this->defaultConditionClasses(), $this->conditionClasses);
}
建立 INSERT SQL 語句。
例如,`
php $sql = $queryBuilder->insert('user', [
'name' => 'Sam',
'age' => 30,
], $params); `
此方法將正確地跳脫表格和欄位名稱。
public string insert ( $table, $columns, &$params ) | ||
$table (表格) | string (字串) |
新列將要插入的資料表。 |
$columns | array|yii\db\Query |
要插入表格中的欄位資料 (name => value) 或 Query 的實例,以執行 INSERT INTO ... SELECT SQL 陳述式。自 2.0.11 版本起,可以使用傳遞 Query。 |
$params | array |
將由此方法產生的繫結參數。它們應在稍後繫結到 DB 命令。 |
return (傳回) | string (字串) |
INSERT SQL |
---|
public function insert($table, $columns, &$params)
{
return parent::insert($table, $this->normalizeTableRowData($table, $columns), $params);
}
定義於: yii\db\QueryBuilder::prepareInsertSelectSubQuery()
為 INSERT INTO ... SELECT SQL 語句準備 select 子查詢和欄位名稱。
protected array prepareInsertSelectSubQuery ( $columns, $schema, $params = [] ) | ||
$columns | yii\db\Query |
代表 select 查詢的物件。 |
$schema | yii\db\Schema |
Schema 物件,用於引用欄位名稱。 |
$params | array |
要繫結到產生的 SQL 語句的參數。 這些參數將包含在結果中,以及在查詢建構過程中產生的其他參數。 |
return (傳回) | array |
欄位名稱、值和參數的陣列。 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果查詢的 select 不僅包含具名參數。 |
protected function prepareInsertSelectSubQuery($columns, $schema, $params = [])
{
if (!is_array($columns->select) || empty($columns->select) || in_array('*', $columns->select)) {
throw new InvalidArgumentException('Expected select query object with enumerated (named) parameters');
}
list($values, $params) = $this->build($columns, $params);
$names = [];
$values = ' ' . $values;
foreach ($columns->select as $title => $field) {
if (is_string($title)) {
$names[] = $schema->quoteColumnName($title);
} elseif (preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $field, $matches)) {
$names[] = $schema->quoteColumnName($matches[2]);
} else {
$names[] = $schema->quoteColumnName($field);
}
}
return [$names, $values, $params];
}
定義於: yii\db\QueryBuilder::prepareInsertValues()
為 INSERT
SQL 語句準備 VALUES
部分。
protected array prepareInsertValues ( $table, $columns, $params = [] ) | ||
$table (表格) | string (字串) |
新列將要插入的資料表。 |
$columns | array|yii\db\Query |
要插入表格中的欄位資料 (name => value) 或 Query 的實例,以執行 INSERT INTO ... SELECT SQL 陳述式。 |
$params | array |
將由此方法產生的繫結參數。它們應在稍後繫結到 DB 命令。 |
return (傳回) | array |
欄位名稱、佔位符、值和參數的陣列。 |
---|
protected function prepareInsertValues($table, $columns, $params = [])
{
$schema = $this->db->getSchema();
$tableSchema = $schema->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$names = [];
$placeholders = [];
$values = ' DEFAULT VALUES';
if ($columns instanceof Query) {
list($names, $values, $params) = $this->prepareInsertSelectSubQuery($columns, $schema, $params);
} else {
foreach ($columns as $name => $value) {
$names[] = $schema->quoteColumnName($name);
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
if ($value instanceof ExpressionInterface) {
$placeholders[] = $this->buildExpression($value, $params);
} elseif ($value instanceof \yii\db\Query) {
list($sql, $params) = $this->build($value, $params);
$placeholders[] = "($sql)";
} else {
$placeholders[] = $this->bindParam($value, $params);
}
}
}
return [$names, $placeholders, $values, $params];
}
定義於: yii\db\QueryBuilder::prepareUpdateSets()
為 UPDATE
SQL 語句準備 SET
部分。
protected array prepareUpdateSets ( $table, $columns, $params = [] ) | ||
$table (表格) | string (字串) |
要更新的表格。 |
$columns | array |
要更新的欄位資料 (name => value)。 |
$params | array |
綁定參數將由此方法修改,以便稍後可以綁定到 DB 命令。 |
return (傳回) | array |
|
---|
protected function prepareUpdateSets($table, $columns, $params = [])
{
$tableSchema = $this->db->getTableSchema($table);
$columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
$sets = [];
foreach ($columns as $name => $value) {
$value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
if ($value instanceof ExpressionInterface) {
$placeholder = $this->buildExpression($value, $params);
} else {
$placeholder = $this->bindParam($value, $params);
}
$sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
}
return [$sets, $params];
}
protected array prepareUpsertColumns ( $table, $insertColumns, $updateColumns, &$constraints = [] ) | ||
$table (表格) | string (字串) | |
$insertColumns | array|yii\db\Query | |
$updateColumns | array|boolean | |
$constraints | yii\db\Constraint[] |
此參數接收一個匹配的約束列表。約束將依其欄位名稱保持唯一。 |
protected function prepareUpsertColumns($table, $insertColumns, $updateColumns, &$constraints = [])
{
if ($insertColumns instanceof Query) {
list($insertNames) = $this->prepareInsertSelectSubQuery($insertColumns, $this->db->getSchema());
} else {
$insertNames = array_map([$this->db, 'quoteColumnName'], array_keys($insertColumns));
}
$uniqueNames = $this->getTableUniqueColumnNames($table, $insertNames, $constraints);
$uniqueNames = array_map([$this->db, 'quoteColumnName'], $uniqueNames);
if ($updateColumns !== true) {
return [$uniqueNames, $insertNames, null];
}
return [$uniqueNames, $insertNames, array_diff($insertNames, $uniqueNames)];
}
定義於: yii\db\QueryBuilder::renameColumn()
建立 SQL 語句,用於重新命名資料行。
public string renameColumn ( $table, $oldName, $newName ) | ||
$table (表格) | string (字串) |
要重新命名欄位的表格。名稱將由此方法正確引用。 |
$oldName | string (字串) |
欄位的舊名稱。名稱將由此方法正確引用。 |
$newName | string (字串) |
欄位的新名稱。名稱將由此方法正確引用。 |
return (傳回) | string (字串) |
用於重新命名資料庫欄位的 SQL 陳述式。 |
---|
public function renameColumn($table, $oldName, $newName)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' RENAME COLUMN ' . $this->db->quoteColumnName($oldName)
. ' TO ' . $this->db->quoteColumnName($newName);
}
建立 SQL 語句,用於重新命名資料庫表格。
public string renameTable ( $oldName, $newName ) | ||
$oldName | string (字串) |
要重新命名的表格。名稱將由此方法正確引用。 |
$newName | string (字串) |
新的表格名稱。名稱將由此方法正確引用。 |
return (傳回) | string (字串) |
用於重新命名資料庫表格的 SQL 陳述式。 |
---|
public function renameTable($oldName, $newName)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($oldName) . ' RENAME TO ' . $this->db->quoteTableName($newName);
}
建立 SQL 語句,用於重設表格主鍵的序號值。
序列將被重設,以便下一個插入的新資料列的主鍵將具有指定的值或 1。
public string resetSequence ( $tableName, $value = null ) | ||
$tableName | string (字串) |
要重設主鍵序列的表格名稱 |
$value (值) | mixed (混合型) |
下一個插入的新資料列的主鍵值。如果未設定,則下一個新資料列的主鍵值將為 1。 |
return (傳回) | string (字串) |
用於重設序列的 SQL 陳述式 |
---|---|---|
throws (拋出) | yii\base\InvalidArgumentException |
如果表格不存在,或沒有與表格關聯的序列。 |
public function resetSequence($tableName, $value = null)
{
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
// c.f. https://postgresql.dev.org.tw/docs/8.1/functions-sequence.html
$sequence = $this->db->quoteTableName($table->sequenceName);
$tableName = $this->db->quoteTableName($tableName);
if ($value === null) {
$key = $this->db->quoteColumnName(reset($table->primaryKey));
$value = "(SELECT COALESCE(MAX({$key}),0) FROM {$tableName})+1";
} else {
$value = (int) $value;
}
return "SELECT SETVAL('$sequence',$value,false)";
} elseif ($table === null) {
throw new InvalidArgumentException("Table not found: $tableName");
}
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
}
定義於: yii\db\QueryBuilder::selectExists()
建立 SELECT EXISTS() SQL 語句。
public string selectExists ( $rawSql ) | ||
$rawSql | string (字串) |
要從中選取的原始形式的子查詢。 |
return (傳回) | string (字串) |
SELECT EXISTS() SQL 陳述式。 |
---|
public function selectExists($rawSql)
{
return 'SELECT EXISTS(' . $rawSql . ')';
}
定義於: yii\db\QueryBuilder::setConditionClasses()
設定 $conditionClasses 屬性的 setter。
另請參閱 $conditionClasses。
public void setConditionClasses ( $classes ) | ||
$classes | string (字串)[] |
條件別名到條件類別的映射。例如
|
public function setConditionClasses($classes)
{
$this->conditionClasses = array_merge($this->conditionClasses, $classes);
}
定義於: yii\db\QueryBuilder::setExpressionBuilders()
設定 $expressionBuilders 屬性的 setter。
另請參閱 $expressionBuilders。
public void setExpressionBuilders ( $builders ) | ||
$builders | string (字串)[] |
應該與 $expressionBuilders 屬性中預定義的 builder 合併的 builder 陣列。 |
public function setExpressionBuilders($builders)
{
$this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
}
建立 SQL 語句,用於截斷資料庫表格。
明確地重新啟動 PGSQL 的身分識別,以與其他預設執行此操作的所有資料庫保持一致。
public string truncateTable ( $table ) | ||
$table (表格) | string (字串) |
要截斷的表格。名稱將由此方法正確引用。 |
return (傳回) | string (字串) |
用於截斷資料庫表格的 SQL 陳述式。 |
---|
public function truncateTable($table)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table) . ' RESTART IDENTITY';
}
建立 UPDATE SQL 語句。
例如:
$params = [];
$sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
此方法將正確地跳脫表格和欄位名稱。
public string update ( $table, $columns, $condition, &$params ) | ||
$table (表格) | string (字串) |
要更新的表格。 |
$columns | array |
要更新的欄位資料 (name => value)。 |
$condition | array|string |
將放在 WHERE 部分的條件。請參閱 yii\db\Query::where() 了解如何指定條件。 |
$params | array |
綁定參數將由此方法修改,以便稍後可以綁定到 DB 命令。 |
return (傳回) | string (字串) |
UPDATE SQL |
---|
public function update($table, $columns, $condition, &$params)
{
return parent::update($table, $this->normalizeTableRowData($table, $columns), $condition, $params);
}
建立 SQL 語句,用於將資料列插入資料庫表格(如果資料列尚不存在,並符合唯一性約束),或在資料列已存在時更新它們。
例如:
$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/', // url is unique
'visits' => 0,
], [
'visits' => new \yii\db\Expression('visits + 1'),
], $params);
此方法將正確地跳脫表格和欄位名稱。
另請參閱
public string upsert ( $table, $insertColumns, $updateColumns, &$params ) | ||
$table (表格) | string (字串) |
新資料列將被插入/更新的表格。 |
$insertColumns | array|yii\db\Query |
要插入表格中的欄位資料 (name => value) 或 yii\db\Query 的實例,以執行 |
$updateColumns | array|boolean |
如果欄位資料已存在,則要更新的欄位資料 (name => value)。如果傳遞 |
$params | array |
將由此方法產生的繫結參數。它們應在稍後繫結到 DB 命令。 |
return (傳回) | string (字串) |
產生的 SQL。 |
---|---|---|
throws (拋出) | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能。 |
public function upsert($table, $insertColumns, $updateColumns, &$params)
{
$insertColumns = $this->normalizeTableRowData($table, $insertColumns);
if (!is_bool($updateColumns)) {
$updateColumns = $this->normalizeTableRowData($table, $updateColumns);
}
if (version_compare($this->db->getServerVersion(), '9.5', '<')) {
return $this->oldUpsert($table, $insertColumns, $updateColumns, $params);
}
return $this->newUpsert($table, $insertColumns, $updateColumns, $params);
}
註冊 或 登入 以進行評論。