クラス yii\db\cubrid\QueryBuilder
継承 | yii\db\cubrid\QueryBuilder » yii\db\QueryBuilder » yii\base\BaseObject |
---|---|
実装 | yii\base\Configurable |
利用可能なバージョン | 2.0 |
ソースコード | https://github.com/yiisoft/yii2/blob/master/framework/db/cubrid/QueryBuilder.php |
QueryBuilder は、CUBRID データベース(バージョン 9.3.x 以降)のクエリビルダーです。
公開プロパティ
プロパティ | 型 | 説明 | 定義元 |
---|---|---|---|
$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\cubrid\QueryBuilder |
公開メソッド
保護されたメソッド
メソッド | 説明 | 定義元 |
---|---|---|
defaultConditionClasses() | デフォルトの条件クラスの配列を含みます。クエリビルダーのデフォルトの条件クラスを変更したい場合は、このメソッドを拡張してください。$conditionClassesのドキュメントを参照してください。 | yii\db\QueryBuilder |
defaultExpressionBuilders() | デフォルトの式ビルダーの配列を含みます。このクエリビルダーのデフォルトの式ビルダーを変更したい場合は、このメソッドを拡張してオーバーライドしてください。$expressionBuildersのドキュメントを参照してください。 | yii\db\cubrid\QueryBuilder |
extractAlias() | テーブルエイリアスが存在する場合はそれを抽出するか、falseを返します。 | yii\db\QueryBuilder |
hasLimit() | 指定された制限が有効かどうかを確認します。 | yii\db\QueryBuilder |
hasOffset() | 指定されたオフセットが有効かどうかを確認します。 | yii\db\QueryBuilder |
prepareInsertSelectSubQuery() | INSERT INTO ... SELECT SQL文のselect-subqueryとフィールド名を準備します。 | yii\db\QueryBuilder |
prepareInsertValues() | INSERT SQL文のVALUES 部分を準備します。 |
yii\db\QueryBuilder |
prepareUpdateSets() | UPDATE SQL文のSET 部分を準備します。 |
yii\db\QueryBuilder |
prepareUpsertColumns() | yii\db\QueryBuilder |
プロパティの詳細
抽象的な列型(キー)から物理的な列型(値)へのマッピング。
\yii\db\cubrid\Schema::TYPE_PK => 'int NOT NULL AUTO_INCREMENT PRIMARY KEY',
\yii\db\cubrid\Schema::TYPE_UPK => 'int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
\yii\db\cubrid\Schema::TYPE_BIGPK => 'bigint NOT NULL AUTO_INCREMENT PRIMARY KEY',
\yii\db\cubrid\Schema::TYPE_UBIGPK => 'bigint UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY',
\yii\db\cubrid\Schema::TYPE_CHAR => 'char(1)',
\yii\db\cubrid\Schema::TYPE_STRING => 'varchar(255)',
\yii\db\cubrid\Schema::TYPE_TEXT => 'varchar',
\yii\db\cubrid\Schema::TYPE_TINYINT => 'smallint',
\yii\db\cubrid\Schema::TYPE_SMALLINT => 'smallint',
\yii\db\cubrid\Schema::TYPE_INTEGER => 'int',
\yii\db\cubrid\Schema::TYPE_BIGINT => 'bigint',
\yii\db\cubrid\Schema::TYPE_FLOAT => 'float(7)',
\yii\db\cubrid\Schema::TYPE_DOUBLE => 'double(15)',
\yii\db\cubrid\Schema::TYPE_DECIMAL => 'decimal(10,0)',
\yii\db\cubrid\Schema::TYPE_DATETIME => 'datetime',
\yii\db\cubrid\Schema::TYPE_TIMESTAMP => 'timestamp',
\yii\db\cubrid\Schema::TYPE_TIME => 'time',
\yii\db\cubrid\Schema::TYPE_DATE => 'date',
\yii\db\cubrid\Schema::TYPE_BINARY => 'blob',
\yii\db\cubrid\Schema::TYPE_BOOLEAN => 'smallint',
\yii\db\cubrid\Schema::TYPE_MONEY => 'decimal(19,4)',
]
メソッドの詳細
定義済み: yii\base\BaseObject::__call()
クラスメソッドではない名前付きメソッドを呼び出します。
これはPHPのマジックメソッドであり、未知のメソッドが呼び出された際に暗黙的に呼び出されるため、直接呼び出さないでください。
public mixed __call ( $name, $params ) | ||
$name | string |
メソッド名 |
$params | array |
メソッドパラメータ |
戻り値 | mixed |
メソッドの戻り値 |
---|---|---|
例外 | 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 |
プロパティ名 |
戻り値 | mixed |
プロパティ値 |
---|---|---|
例外 | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
例外 | 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が返されることに注意してください。
こちらも参照してください https://www.php.net/manual/en/function.isset.php.
public boolean __isset ( $name ) | ||
$name | string |
プロパティ名またはイベント名 |
戻り値 | 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 |
プロパティ値 |
例外 | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
---|---|---|
例外 | 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 |
プロパティ名 |
例外 | 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);
}
}
既存のテーブルにチェック制約を追加するためのSQLコマンドを作成します。
public string addCheck ( $name, $table, $expression ) | ||
$name | string |
チェック制約の名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
チェック制約を追加するテーブル。このメソッドによって適切に引用符で囲まれます。 |
$expression | string |
`CHECK`制約のSQL。 |
戻り値 | string |
既存のテーブルにチェック制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
CUBRIDではサポートされていません。 |
public function addCheck($name, $table, $expression)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
}
定義場所: yii\db\QueryBuilder::addColumn()
新しいDB列を追加するための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'になります。 |
戻り値 | string |
新しい列を追加するためのSQL文。 |
---|
public function addColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' ADD ' . $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
列にコメントを追加するためのSQLコマンドを構築します。
public string addCommentOnColumn ( $table, $column, $comment ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名は、このメソッドによって適切に引用符で囲まれます。 |
$column | string |
コメントを追加する列の名前。列名は、このメソッドによって適切に引用符で囲まれます。 |
$comment | string |
追加するコメントのテキスト。コメントは、このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
列にコメントを追加するためのSQL文 |
---|
public function addCommentOnColumn($table, $column, $comment)
{
$definition = $this->getColumnDefinition($table, $column);
$definition = trim(preg_replace("/COMMENT '(.*?)'/i", '', $definition));
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' CHANGE ' . $this->db->quoteColumnName($column)
. ' ' . $this->db->quoteColumnName($column)
. (empty($definition) ? '' : ' ' . $definition)
. ' COMMENT ' . $this->db->quoteValue($comment);
}
テーブルにコメントを追加するためのSQLコマンドを構築します。
public string addCommentOnTable ( $table, $comment ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名は、このメソッドによって適切に引用符で囲まれます。 |
$comment | string |
追加するコメントのテキスト。コメントは、このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
テーブルにコメントを追加するためのSQL文 |
---|
public function addCommentOnTable($table, $comment)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' COMMENT ' . $this->db->quoteValue($comment);
}
定義場所: yii\db\QueryBuilder::addDefaultValue()
既存のテーブルにデフォルト値制約を追加するためのSQLコマンドを作成します。
public string addDefaultValue ( $name, $table, $column, $value ) | ||
$name | string |
デフォルト値制約の名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
デフォルト値制約を追加するテーブル。このメソッドによって適切に引用符で囲まれます。 |
$column | string |
制約を追加する列の名前。このメソッドによって適切に引用符で囲まれます。 |
$value | mixed |
デフォルト値。 |
戻り値 | string |
既存のテーブルにデフォルト値制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
基盤となるDBMSでサポートされていない場合。 |
public function addDefaultValue($name, $table, $column, $value)
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support adding default value constraints.');
}
定義場所: yii\db\QueryBuilder::addForeignKey()
既存のテーブルに外部キー制約を追加するためのSQLステートメントを構築します。
このメソッドは、テーブル名と列名を適切に引用符で囲みます。
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をサポートしています。 |
戻り値 | 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 |
主キーを構成する列名をコンマで区切った文字列、または列名の配列。 |
戻り値 | 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 |
制約が追加される列の名前。複数の列がある場合は、コンマで区切ります。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | 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) . ')';
}
定義位置: yii\db\QueryBuilder::alterColumn()
列の定義を変更するための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」になります。 |
戻り値 | string |
列の定義を変更するためのSQL文。 |
---|
public function alterColumn($table, $column, $type)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' CHANGE '
. $this->db->quoteColumnName($column) . ' '
. $this->db->quoteColumnName($column) . ' '
. $this->getColumnType($type);
}
定義位置: yii\db\QueryBuilder::batchInsert()
バッチ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から存在します。 |
戻り値 | 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 === false) {
$value = 0;
} 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 |
参照渡し |
戻り値 | 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文にバインドされるパラメータ。これらのパラメータは、クエリ構築プロセス中に生成された追加のパラメータと共に結果に含まれます。 |
戻り値 | array |
生成されたSQL文(配列の最初の要素)と、SQL文にバインドされる対応するパラメータ(配列の2番目の要素)。返されるパラメータには、`$params`で提供されたパラメータが含まれます。 |
---|
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];
}
定義位置: yii\db\QueryBuilder::buildAndCondition()
AND
またはOR
演算子で2つ以上のSQL式を接続します。
public string buildAndCondition ( $operator, $operands, &$params ) | ||
$operator | string |
与えられたオペランドを接続するために使用する演算子。 |
$operands | array |
接続するSQL式。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|
public function buildAndCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
定義位置: yii\db\QueryBuilder::buildBetweenCondition()
BETWEEN
演算子を使用したSQL式を作成します。
public string buildBetweenCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子(例:`BETWEEN`または`NOT BETWEEN`) |
$operands | array |
最初のオペランドは列名です。2番目と3番目のオペランドは、列値が含まれるべき範囲を表します。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | 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 |
処理する列。 |
戻り値 | 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 |
設定されるバインディングパラメータ。 |
戻り値 | 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;
}
定義先: yii\db\QueryBuilder::buildExistsCondition()
EXISTS
演算子を使用したSQL式を作成します。
public string buildExistsCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子(例: |
$operands | array |
サブクエリを表すyii\db\Queryオブジェクトを1つだけ含みます。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | 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文にバインドされるパラメータ。これらのパラメータは、式構築プロセス中に生成された追加のパラメータとともに結果に含まれます。 |
戻り値 | string |
DBMSに渡す前に引用符で囲まれたり、エンコードされたりしないSQL文 |
---|---|---|
例外 | yii\base\InvalidArgumentException |
$expressionの構築がこのQueryBuilderでサポートされていない場合。 |
public function buildExpression(ExpressionInterface $expression, &$params = [])
{
$builder = $this->getExpressionBuilder($expression);
return $builder->build($expression, $params);
}
public string buildFrom ( $tables, &$params ) | ||
$tables | array | |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | 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 | |
戻り値 | 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);
}
定義先: yii\db\QueryBuilder::buildHashCondition()
列と値のペアに基づいて条件を作成します。
public string buildHashCondition ( $condition, &$params ) | ||
$condition | array |
条件の指定。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|
public function buildHashCondition($condition, &$params)
{
return $this->buildCondition(new HashCondition($condition), $params);
}
public string buildHaving ( $condition, &$params ) | ||
$condition | string|array | |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
yii\db\Query::$havingから構築されたHAVING句。 |
---|
public function buildHaving($condition, &$params)
{
$having = $this->buildCondition($condition, $params);
return $having === '' ? '' : 'HAVING ' . $having;
}
定義先: yii\db\QueryBuilder::buildInCondition()
IN
演算子を使用したSQL式を作成します。
public string buildInCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子(例: |
$operands | array |
最初のオペランドは列名です。配列の場合、複合IN条件が生成されます。2番目のオペランドは、列の値が属するべき値の配列です。空の配列の場合、生成された式は、演算子が |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | 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 |
設定されるバインディングパラメータ。 |
戻り値 | string |
yii\db\Query::$joinから構築されたJOIN句。 |
---|---|---|
例外 | 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);
}
定義先: yii\db\QueryBuilder::buildLikeCondition()
LIKE
演算子を使用したSQL式を作成します。
public string buildLikeCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子(例: |
$operands | array |
2つまたは3つのオペランドの配列
|
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | yii\base\InvalidArgumentException |
間違った数のオペランドが与えられた場合。 |
public function buildLikeCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildLimit ( $limit, $offset ) | ||
$limit | 整数 | |
$offset | 整数 | |
戻り値 | string |
LIMIT句とOFFSET句 |
---|
public function buildLimit($limit, $offset)
{
$sql = '';
// limit is not optional in CUBRID
// https://www.cubrid.org/manual/en/9.3.0/sql/query/select.html#limit-clause
// "You can specify a very big integer for row_count to display to the last row, starting from a specific row."
if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
if ($this->hasOffset($offset)) {
$sql .= ' OFFSET ' . $offset;
}
} elseif ($this->hasOffset($offset)) {
$sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
}
return $sql;
}
定義場所: yii\db\QueryBuilder::buildNotCondition()
NOT
演算子でSQL式を反転します。
public string buildNotCondition ( $operator, $operands, &$params ) | ||
$operator | string |
与えられたオペランドを接続するために使用する演算子。 |
$operands | array |
接続するSQL式。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | yii\base\InvalidArgumentException |
間違った数のオペランドが与えられた場合。 |
public function buildNotCondition($operator, $operands, &$params)
{
array_unshift($operands, $operator);
return $this->buildCondition($operands, $params);
}
public string buildOrderBy ( $columns ) | ||
$columns | array | |
戻り値 | 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 | 整数 |
制限数。詳細はyii\db\Query::limit()を参照してください。 |
$offset | 整数 |
オフセット数。詳細はyii\db\Query::offset()を参照してください。 |
戻り値 | 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 | |
戻り値 | 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);
}
定義場所: yii\db\QueryBuilder::buildSimpleCondition()
"column" operator value
のようなSQL式を作成します。
public string buildSimpleCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子。例: |
$operands | array |
2つのカラム名を含みます。 |
$params | array |
設定されるバインディングパラメータ。 |
戻り値 | string |
生成されたSQL式。 |
---|---|---|
例外 | 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 |
設定されるバインディングパラメータ。 |
戻り値 | 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 |
設定されるバインディングパラメータ。 |
戻り値 | 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 |
設定されるバインディングパラメータ。 |
戻り値 | 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()
プロパティを読み取ることができるかどうかを示す値を返します。
プロパティは、以下の場合に読み取り可能です。
- クラスが指定された名前に関連付けられたゲッターメソッドを持つ場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが指定された名前のメンバ変数を持つ場合(
$checkVars
がtrueの場合)。
canSetProperty()も参照してください。
public boolean canGetProperty ( $name, $checkVars = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
戻り値 | boolean |
プロパティが読み取り可能かどうか |
---|
public function canGetProperty($name, $checkVars = true)
{
return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}
定義場所: yii\base\BaseObject::canSetProperty()
プロパティを設定できるかどうかを示す値を返します。
プロパティは、以下の場合に書き込み可能です。
- クラスが指定された名前に関連付けられたセッターメソッドを持つ場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが指定された名前のメンバ変数を持つ場合(
$checkVars
がtrueの場合)。
canGetProperty()も参照してください。
public boolean canSetProperty ( $name, $checkVars = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
戻り値 | boolean |
プロパティが書き込み可能かどうか |
---|
public function canSetProperty($name, $checkVars = true)
{
return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}
定義されている場所: yii\db\QueryBuilder::checkIntegrity()
整合性チェックを有効または無効にするためのSQLステートメントを構築します。
public string checkIntegrity ( $check = true, $schema = '', $table = '' ) | ||
$check | boolean |
整合性チェックを有効化または無効化します。 |
$schema | string |
テーブルのスキーマ。デフォルトは空文字列で、現在のスキーマまたはデフォルトのスキーマを意味します。 |
$table | string |
$table |
戻り値 | string |
テーブル名。デフォルトは空文字列で、どのテーブルも変更されないことを意味します。 |
---|---|---|
例外 | yii\base\NotSupportedException |
整合性チェックのためのSQL文 |
public function checkIntegrity($check = true, $schema = '', $table = '')
{
throw new NotSupportedException($this->db->getDriverName() . ' does not support enabling/disabling integrity check.');
}
::class
を使用してください。
定義されている場所: yii\base\BaseObject::className()
このクラスの完全修飾名を返します。
public static string className ( ) | ||
戻り値 | string |
このクラスの完全修飾名。 |
---|
public static function className()
{
return get_called_class();
}
定義されている場所: yii\db\QueryBuilder::createConditionFromArray()
yii\db\Query::where()で説明されている配列形式で定義された$conditionを、$conditionClassesマップに従って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);
}
定義されている場所: yii\db\QueryBuilder::createIndex()
新しいインデックスを作成するためのSQL文を構築します。
public string createIndex ( $name, $table, $columns, $unique = false ) | ||
$name | string |
インデックスの名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
新しいインデックスが作成されるテーブル。テーブル名は、このメソッドによって適切に引用符で囲まれます。 |
$columns | string|array |
インデックスに含める列。複数の列がある場合は、コンマで区切る、または配列を使用して表現します。各列名は、名前に括弧がない限り、このメソッドによって適切に引用符で囲まれます。 |
$unique | boolean |
作成されたインデックスにUNIQUE制約を追加するかどうか。 |
戻り値 | string |
新しいインデックスを作成するためのSQL文。 |
---|
public function createIndex($name, $table, $columns, $unique = false)
{
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->db->quoteTableName($name) . ' ON '
. $this->db->quoteTableName($table)
. ' (' . $this->buildColumns($columns) . ')';
}
定義されている場所: yii\db\QueryBuilder::createTable()
新しいDBテーブルを作成するための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 |
新しいテーブルの列(name => definition)。 |
$options | string|null |
生成されたSQLに追加される追加のSQLフラグメント。 |
戻り値 | 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オブジェクトのいずれかです。 |
戻り値 | 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;
}
定義されている場所: yii\db\QueryBuilder::defaultConditionClasses()
デフォルトの条件クラスの配列を含みます。クエリビルダーのデフォルトの条件クラスを変更したい場合は、このメソッドを拡張してください。$conditionClassesのドキュメントを参照してください。
こちらも参照してください $conditionClasses.
protected array defaultConditionClasses ( ) |
protected function defaultConditionClasses()
{
return [
'NOT' => 'yii\db\conditions\NotCondition',
'AND' => 'yii\db\conditions\AndCondition',
'OR' => 'yii\db\conditions\OrCondition',
'BETWEEN' => 'yii\db\conditions\BetweenCondition',
'NOT BETWEEN' => 'yii\db\conditions\BetweenCondition',
'IN' => 'yii\db\conditions\InCondition',
'NOT IN' => 'yii\db\conditions\InCondition',
'LIKE' => 'yii\db\conditions\LikeCondition',
'NOT LIKE' => 'yii\db\conditions\LikeCondition',
'OR LIKE' => 'yii\db\conditions\LikeCondition',
'OR NOT LIKE' => 'yii\db\conditions\LikeCondition',
'EXISTS' => 'yii\db\conditions\ExistsCondition',
'NOT EXISTS' => 'yii\db\conditions\ExistsCondition',
];
}
デフォルトの式ビルダーの配列を含みます。このクエリビルダーのデフォルトの式ビルダーを変更したい場合は、このメソッドを拡張してオーバーライドしてください。$expressionBuildersのドキュメントを参照してください。
protected array defaultExpressionBuilders ( ) |
protected function defaultExpressionBuilders()
{
return array_merge(parent::defaultExpressionBuilders(), [
'yii\db\conditions\LikeCondition' => 'yii\db\cubrid\conditions\LikeConditionBuilder',
]);
}
定義されている場所: 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コマンドにバインドするために使用されます。 |
戻り値 | 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;
}
チェック制約を削除するためのSQLコマンドを作成します。
public string dropCheck ( $name, $table ) | ||
$name | string |
削除するチェック制約の名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
チェック制約を削除するテーブルの名前。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
チェック制約を削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
CUBRIDではサポートされていません。 |
public function dropCheck($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by CUBRID.');
}
定義されている場所: yii\db\QueryBuilder::dropColumn()
DB列を削除するためのSQL文を構築します。
public string dropColumn ( $table, $column ) | ||
$table | string |
削除する列を持つテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
$column | string |
削除する列の名前。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DB列を削除するためのSQL文。 |
---|
public function dropColumn($table, $column)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP COLUMN ' . $this->db->quoteColumnName($column);
}
列にコメントを追加するためのSQLコマンドを構築します。
public string dropCommentFromColumn ( $table, $column ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名は、このメソッドによって適切に引用符で囲まれます。 |
$column | string |
コメントを追加する列の名前。列名は、このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
列にコメントを追加するためのSQL文 |
---|
public function dropCommentFromColumn($table, $column)
{
return $this->addCommentOnColumn($table, $column, '');
}
テーブルにコメントを追加するためのSQLコマンドを構築します。
public string dropCommentFromTable ( $table ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名は、このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
列にコメントを追加するためのSQL文 |
---|
public function dropCommentFromTable($table)
{
return $this->addCommentOnTable($table, '');
}
定義位置: yii\db\QueryBuilder::dropDefaultValue()
デフォルト値制約を削除するためのSQLコマンドを作成します。
public string dropDefaultValue ( $name, $table ) | ||
$name | string |
削除するデフォルト値制約の名前。名前はメソッドによって適切に引用符で囲まれます。 |
$table | string |
デフォルト値制約を削除するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
デフォルト値制約を削除するためのSQL文。 |
---|---|---|
例外 | 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 |
外部キーを削除するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
外部キー制約を削除するためのSQL文。 |
---|
public function dropForeignKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
インデックスを削除するためのSQL文を構築します。
参考: https://www.cubrid.org/manual/en/9.3.0/sql/schema/table.html#drop-index-clause.
public string dropIndex ( $name, $table ) | ||
$name | string |
削除するインデックスの名前。名前はメソッドによって適切に引用符で囲まれます。 |
$table | string |
インデックスを削除するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
インデックスを削除するためのSQL文。 |
---|
public function dropIndex($name, $table)
{
/** @var Schema $schema */
$schema = $this->db->getSchema();
foreach ($schema->getTableUniques($table) as $unique) {
if ($unique->name === $name) {
return $this->dropUnique($name, $table);
}
}
return 'DROP INDEX ' . $this->db->quoteTableName($name) . ' ON ' . $this->db->quoteTableName($table);
}
定義位置: yii\db\QueryBuilder::dropPrimaryKey()
既存のテーブルから主キー制約を削除するためのSQL文を構築します。
public string dropPrimaryKey ( $name, $table ) | ||
$name | string |
削除する主キー制約の名前。 |
$table | string |
主キー制約を削除するテーブル。 |
戻り値 | string |
既存のテーブルから主キー制約を削除するためのSQL文。 |
---|
public function dropPrimaryKey($name, $table)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table)
. ' DROP CONSTRAINT ' . $this->db->quoteColumnName($name);
}
定義位置: yii\db\QueryBuilder::dropTable()
DBテーブルを削除するためのSQL文を構築します。
public string dropTable ( $table ) | ||
$table | string |
削除するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | 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 |
一意制約を削除するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | 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 |
削除するビューの名前。 |
戻り値 | string |
|
---|
public function dropView($viewName)
{
return 'DROP VIEW ' . $this->db->quoteTableName($viewName);
}
定義位置: yii\db\QueryBuilder::executeResetSequence()
テーブルの主キーのシーケンス値をリセットするためのSQL文を実行します。
実行の理由は、一部のデータベース(Oracleなど)ではこれを行うために複数のクエリが必要なためです。シーケンスは、挿入される次の新しい行の主キーが指定された値、または既存の最大値+1になるようにリセットされます。
public void executeResetSequence ( $table, $value = null ) | ||
$table | string |
主キーシーケンスをリセットするテーブルの名前 |
$value | array|string|null |
挿入される次の新しい行の主キーの値。これが設定されていない場合、次の新しい行の主キーは、既存の最大値 + 1 になります。 |
例外 | yii\base\NotSupportedException |
整合性チェックのためのSQL文 |
---|
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
: string型、"varchar(255)"に変換されます。text
: 長いstring型、"text"に変換されます。smallint
: 小さい整数型、"smallint(6)"に変換されます。integer
: 整数型、"int(11)"に変換されます。bigint
: 大きい整数型、"bigint(20)"に変換されます。boolean
: boolean型、"tinyint(1)"に変換されます。float
`: 浮動小数点数型、"float"に変換されます。decimal
: 10進数型、"decimal"に変換されます。datetime
: datetime型、"datetime"に変換されます。timestamp
: timestamp型、"timestamp"に変換されます。time
: time型、"time"に変換されます。date
: date型、"date"に変換されます。money
: money型、"decimal(19,4)"に変換されます。binary
: バイナリデータ型、"blob"に変換されます。
抽象型がスペースで区切られた2つ以上の部分を含む場合(例:"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 |
抽象的なカラム型 |
戻り値 | 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 配列を使用して、適切なビルダークラスを検索します。
こちらも参照してください $expressionBuilders。
public yii\db\ExpressionBuilderInterface getExpressionBuilder ( yii\db\ExpressionInterface $expression ) | ||
$expression | yii\db\ExpressionInterface | |
例外 | yii\base\InvalidArgumentException |
$expressionの構築がこのQueryBuilderでサポートされていない場合。 |
---|
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()
指定された制限が有効かどうかを確認します。
protected boolean hasLimit ( $limit ) | ||
$limit | mixed |
指定されたlimit |
戻り値 | 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 |
メソッド名 |
戻り値 | boolean |
メソッドが定義されているかどうか |
---|
public function hasMethod($name)
{
return method_exists($this, $name);
}
定義場所: yii\db\QueryBuilder::hasOffset()
指定されたオフセットが有効かどうかを確認します。
protected boolean hasOffset ( $offset ) | ||
$offset | mixed |
指定されたoffset |
戻り値 | boolean |
offsetが有効かどうか |
---|
protected function hasOffset($offset)
{
return ($offset instanceof ExpressionInterface) || ctype_digit((string)$offset) && (string)$offset !== '0';
}
定義場所: yii\base\BaseObject::hasProperty()
プロパティが定義されているかどうかを示す値を返します。
プロパティは、以下の場合に定義されます。
- クラスに、指定された名前と関連付けられたゲッターまたはセッターメソッドがある場合(この場合、プロパティ名は大文字と小文字が区別されません)。
- クラスが指定された名前のメンバ変数を持つ場合(
$checkVars
がtrueの場合)。
参照
public boolean hasProperty ( $name, $checkVars = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
戻り値 | 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);
}
定義先: yii\db\QueryBuilder::insert()
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) 、または INSERT INTO ... SELECT SQL文を実行するためのQueryのインスタンス。 Queryの受け渡しは、バージョン2.0.11から利用可能です。 |
$params | array |
このメソッドによって生成されるバインディングパラメータ。後でDBコマンドにバインドする必要があります。 |
戻り値 | string |
INSERT SQL文 |
---|
public function insert($table, $columns, &$params)
{
list($names, $placeholders, $values, $params) = $this->prepareInsertValues($table, $columns, $params);
return 'INSERT INTO ' . $this->db->quoteTableName($table)
. (!empty($names) ? ' (' . implode(', ', $names) . ')' : '')
. (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
}
定義先: yii\db\QueryBuilder::prepareInsertSelectSubQuery()
INSERT INTO ... SELECT SQL文のselect-subqueryとフィールド名を準備します。
protected array prepareInsertSelectSubQuery ( $columns, $schema, $params = [] ) | ||
$columns | yii\db\Query |
selectクエリを表すオブジェクト。 |
$schema | yii\db\Schema |
カラム名をクォートするためのSchemaオブジェクト。 |
$params | array |
生成されたSQL文にバインドされるパラメータ。これらのパラメータは、クエリ構築プロセス中に生成された追加のパラメータと共に結果に含まれます。 |
戻り値 | array |
カラム名、値、パラメータの配列。 |
---|---|---|
例外 | yii\base\InvalidArgumentException |
クエリに名前付きパラメータのみが含まれていない場合。 |
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) 、または INSERT INTO ... SELECT SQL文を実行するためのQueryのインスタンス。 |
$params | array |
このメソッドによって生成されるバインディングパラメータ。後でDBコマンドにバインドする必要があります。 |
戻り値 | 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コマンドにバインドするために使用されます。 |
戻り値 | 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 |
カラムの新しい名前。名前はメソッドによって適切にクォートされます。 |
戻り値 | string |
DBカラムの名前変更のための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);
}
定義先: yii\db\QueryBuilder::renameTable()
DBテーブルの名前を変更するためのSQL文を構築します。
public string renameTable ( $oldName, $newName ) | ||
$oldName | string |
名前を変更するテーブル。名前はメソッドによって適切にクォートされます。 |
$newName | string |
新しいテーブル名。名前はメソッドによって適切にクォートされます。 |
戻り値 | string |
DBテーブルの名前変更のためのSQL文。 |
---|
public function renameTable($oldName, $newName)
{
return 'RENAME TABLE ' . $this->db->quoteTableName($oldName) . ' TO ' . $this->db->quoteTableName($newName);
}
テーブルの主キーのシーケンス値をリセットするためのSQL文を作成します。
シーケンスは、挿入される次の新しい行の主キーが指定された値または1を持つようにリセットされます。
public string resetSequence ( $tableName, $value = null ) | ||
$tableName | string |
主キーシーケンスをリセットするテーブルの名前 |
$value | mixed |
挿入される次の新しい行の主キーの値。これが設定されていない場合、次の新しい行の主キーの値は1になります。 |
戻り値 | string |
シーケンスをリセットするためのSQL文 |
---|---|---|
例外 | yii\base\InvalidArgumentException |
テーブルが存在しない場合、またはテーブルに関連付けられたシーケンスがない場合。 |
public function resetSequence($tableName, $value = null)
{
$table = $this->db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
$tableName = $this->db->quoteTableName($tableName);
if ($value === null) {
$key = reset($table->primaryKey);
$value = (int) $this->db->createCommand("SELECT MAX(`$key`) FROM " . $this->db->schema->quoteTableName($tableName))->queryScalar() + 1;
} else {
$value = (int) $value;
}
return 'ALTER TABLE ' . $this->db->schema->quoteTableName($tableName) . " AUTO_INCREMENT=$value;";
} elseif ($table === null) {
throw new InvalidArgumentException("Table not found: $tableName");
}
throw new InvalidArgumentException("There is not sequence associated with table '$tableName'.");
}
SELECT EXISTS() SQL文を作成します。
public string selectExists ( $rawSql ) | ||
$rawSql | string |
raw形式のサブクエリ。 |
戻り値 | string |
SELECT EXISTS() SQL文。 |
---|
public function selectExists($rawSql)
{
return 'SELECT CASE WHEN EXISTS(' . $rawSql . ') THEN 1 ELSE 0 END';
}
定義先: yii\db\QueryBuilder::setConditionClasses()
$conditionClassesプロパティのセッターです。
こちらも参照してください $conditionClasses.
public void setConditionClasses ( $classes ) | ||
$classes | string[] |
条件のエイリアスと条件クラスのマッピング。例:
|
public function setConditionClasses($classes)
{
$this->conditionClasses = array_merge($this->conditionClasses, $classes);
}
定義先: yii\db\QueryBuilder::setExpressionBuilders()
$expressionBuildersプロパティのセッターです。
こちらも参照してください $expressionBuilders。
public void setExpressionBuilders ( $builders ) | ||
$builders | string[] |
$expressionBuilders プロパティで事前に定義されているビルダーとマージされるべきビルダーの配列。 |
public function setExpressionBuilders($builders)
{
$this->expressionBuilders = array_merge($this->expressionBuilders, $builders);
}
定義先: yii\db\QueryBuilder::truncateTable()
DBテーブルを切り捨てるためのSQL文を構築します。
public string truncateTable ( $table ) | ||
$table | string |
切り捨てるテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DBテーブルを切り捨てるためのSQL文。 |
---|
public function truncateTable($table)
{
return 'TRUNCATE TABLE ' . $this->db->quoteTableName($table);
}
定義先: yii\db\QueryBuilder::update()
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コマンドにバインドするために使用されます。 |
戻り値 | string |
UPDATE SQL |
---|
public function update($table, $columns, $condition, &$params)
{
list($lines, $params) = $this->prepareUpdateSets($table, $columns, $params);
$sql = 'UPDATE ' . $this->db->quoteTableName($table) . ' SET ' . implode(', ', $lines);
$where = $this->buildWhere($condition, $params);
return $where === '' ? $sql : $sql . ' ' . $where;
}
データベーステーブルに、まだ存在しない行(一意制約に一致する)を挿入するか、存在する場合は更新するための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);
このメソッドは、テーブル名と列名を適切にエスケープします。
参照: https://www.cubrid.org/manual/en/9.3.0/sql/query/merge.html.
public string upsert ( $table, $insertColumns, $updateColumns, &$params ) | ||
$table | string |
新しい行が挿入/更新されるテーブル。 |
$insertColumns | array|yii\db\Query |
テーブルに挿入される列データ(名前 => 値)、または`INSERT INTO ... SELECT` SQL文を実行するためのyii\db\Queryのインスタンス。 |
$updateColumns | array|boolean |
列データが既に存在する場合に更新される列データ(名前 => 値)。`true`が渡された場合、列データは挿入列データと一致するように更新されます。`false`が渡された場合、列データが既に存在する場合は更新されません。 |
$params | array |
このメソッドによって生成されるバインディングパラメータ。後でDBコマンドにバインドする必要があります。 |
戻り値 | string |
結果のSQL。 |
---|---|---|
例外 | yii\base\NotSupportedException |
基盤となるDBMSでサポートされていない場合。 |
public function upsert($table, $insertColumns, $updateColumns, &$params)
{
/** @var Constraint[] $constraints */
list($uniqueNames, $insertNames, $updateNames) = $this->prepareUpsertColumns($table, $insertColumns, $updateColumns, $constraints);
if (empty($uniqueNames)) {
return $this->insert($table, $insertColumns, $params);
}
if ($updateNames === []) {
// there are no columns to update
$updateColumns = false;
}
$onCondition = ['or'];
$quotedTableName = $this->db->quoteTableName($table);
foreach ($constraints as $constraint) {
$constraintCondition = ['and'];
foreach ($constraint->columnNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
$constraintCondition[] = "$quotedTableName.$quotedName=\"EXCLUDED\".$quotedName";
}
$onCondition[] = $constraintCondition;
}
$on = $this->buildCondition($onCondition, $params);
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
$mergeSql = 'MERGE INTO ' . $this->db->quoteTableName($table) . ' '
. 'USING (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') AS "EXCLUDED" (' . implode(', ', $insertNames) . ') '
. "ON ($on)";
$insertValues = [];
foreach ($insertNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
if (strrpos($quotedName, '.') === false) {
$quotedName = '"EXCLUDED".' . $quotedName;
}
$insertValues[] = $quotedName;
}
$insertSql = 'INSERT (' . implode(', ', $insertNames) . ')'
. ' VALUES (' . implode(', ', $insertValues) . ')';
if ($updateColumns === false) {
return "$mergeSql WHEN NOT MATCHED THEN $insertSql";
}
if ($updateColumns === true) {
$updateColumns = [];
foreach ($updateNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
if (strrpos($quotedName, '.') === false) {
$quotedName = '"EXCLUDED".' . $quotedName;
}
$updateColumns[$name] = new Expression($quotedName);
}
}
list($updates, $params) = $this->prepareUpdateSets($table, $updateColumns, $params);
$updateSql = 'UPDATE SET ' . implode(', ', $updates);
return "$mergeSql WHEN MATCHED THEN $updateSql WHEN NOT MATCHED THEN $insertSql";
}
サインアップ または ログイン してコメントしてください。