クラス yii\db\sqlite\QueryBuilder
継承 | yii\db\sqlite\QueryBuilder » yii\db\QueryBuilder » yii\base\BaseObject |
---|---|
実装 | yii\base\Configurable |
利用可能バージョン | 2.0 |
ソースコード | https://github.com/yiisoft/yii2/blob/master/framework/db/sqlite/QueryBuilder.php |
QueryBuilder は、SQLite データベースのクエリビルダーです。
公開プロパティ
プロパティ | 型 | 説明 | 定義元 |
---|---|---|---|
$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\sqlite\QueryBuilder |
公開メソッド
保護されたメソッド
メソッド | 説明 | 定義元 |
---|---|---|
defaultConditionClasses() | デフォルトの条件クラスの配列を含みます。クエリビルダーのデフォルトの条件クラスを変更したい場合は、このメソッドを拡張してください。$conditionClassesのドキュメントを参照してください。 | yii\db\QueryBuilder |
defaultExpressionBuilders() | デフォルトの式ビルダーの配列を含みます。このクエリビルダーのデフォルトの式ビルダーを変更したい場合は、このメソッドを拡張してオーバーライドしてください。$expressionBuildersのドキュメントを参照してください。 | yii\db\sqlite\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 |
プロパティの詳細
抽象的なカラム型(キー)から物理的なカラム型(値)へのマッピング。
\yii\db\sqlite\Schema::TYPE_PK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
\yii\db\sqlite\Schema::TYPE_UPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
\yii\db\sqlite\Schema::TYPE_BIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
\yii\db\sqlite\Schema::TYPE_UBIGPK => 'integer PRIMARY KEY AUTOINCREMENT NOT NULL',
\yii\db\sqlite\Schema::TYPE_CHAR => 'char(1)',
\yii\db\sqlite\Schema::TYPE_STRING => 'varchar(255)',
\yii\db\sqlite\Schema::TYPE_TEXT => 'text',
\yii\db\sqlite\Schema::TYPE_TINYINT => 'tinyint',
\yii\db\sqlite\Schema::TYPE_SMALLINT => 'smallint',
\yii\db\sqlite\Schema::TYPE_INTEGER => 'integer',
\yii\db\sqlite\Schema::TYPE_BIGINT => 'bigint',
\yii\db\sqlite\Schema::TYPE_FLOAT => 'float',
\yii\db\sqlite\Schema::TYPE_DOUBLE => 'double',
\yii\db\sqlite\Schema::TYPE_DECIMAL => 'decimal(10,0)',
\yii\db\sqlite\Schema::TYPE_DATETIME => 'datetime',
\yii\db\sqlite\Schema::TYPE_TIMESTAMP => 'timestamp',
\yii\db\sqlite\Schema::TYPE_TIME => 'time',
\yii\db\sqlite\Schema::TYPE_DATE => 'date',
\yii\db\sqlite\Schema::TYPE_BINARY => 'blob',
\yii\db\sqlite\Schema::TYPE_BOOLEAN => 'boolean',
\yii\db\sqlite\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が返されます。
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 |
|
戻り値 | string |
既存のテーブルにチェック制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function addCheck($name, $table, $expression)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
定義位置: 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文 |
---|---|---|
例外 | yii\base\NotSupportedException |
public function addCommentOnColumn($table, $column, $comment)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
テーブルにコメントを追加するためのSQLコマンドを構築します。
public string addCommentOnTable ( $table, $comment ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名はメソッドによって適切に引用符で囲まれます。 |
$comment | string |
追加するコメントのテキスト。コメントはメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
テーブルにコメントを追加するためのSQL文 |
---|---|---|
例外 | yii\base\NotSupportedException |
public function addCommentOnTable($table, $comment)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
既存のテーブルにデフォルト値制約を追加するためのSQLコマンドを作成します。
public string addDefaultValue ( $name, $table, $column, $value ) | ||
$name | string |
デフォルト値制約の名前。この名前は、メソッドによって適切に引用符で囲まれます。 |
$table | string |
デフォルト値制約を追加するテーブル。この名前は、メソッドによって適切に引用符で囲まれます。 |
$column | string |
制約を追加する列の名前。この名前は、メソッドによって適切に引用符で囲まれます。 |
$value | mixed |
デフォルト値。 |
戻り値 | string |
既存のテーブルにデフォルト値制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function addDefaultValue($name, $table, $column, $value)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
既存のテーブルに外部キー制約を追加するための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文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
既存のテーブルに主キー制約を追加するためのSQL文を構築します。
public string addPrimaryKey ( $name, $table, $columns ) | ||
$name | string |
主キー制約の名前。 |
$table | string |
主キー制約を追加するテーブル。 |
$columns | string|array |
主キーを構成する列名のコンマ区切り文字列または配列。 |
戻り値 | string |
既存のテーブルに主キー制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function addPrimaryKey($name, $table, $columns)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
既存のテーブルに一意制約を追加するためのSQLコマンドを作成します。
public string addUnique ( $name, $table, $columns ) | ||
$name | string |
一意制約の名前。この名前は、メソッドによって適切に引用符で囲まれます。 |
$table | string |
一意制約を追加するテーブル。この名前は、メソッドによって適切に引用符で囲まれます。 |
$columns | string|array |
制約を追加する列の名前。複数の列がある場合は、コンマで区切ります。この名前は、メソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
既存のテーブルに一意制約を追加するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function addUnique($name, $table, $columns)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
カラムの定義を変更するための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文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function alterColumn($table, $column, $type)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
バッチINSERT SQL文を生成します。
例えば、
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
各行の値は、対応する列名と一致する必要があります。
public string batchInsert ( $table, $columns, $rows, &$params = [] ) | ||
$table | string |
新しい行が挿入されるテーブル。 |
$columns | array |
列名 |
$rows | array|Generator |
テーブルに一括挿入される行 |
$params | ||
戻り値 | string |
一括INSERT SQL文 |
---|
public function batchInsert($table, $columns, $rows, &$params = [])
{
if (empty($rows)) {
return '';
}
// SQLite supports batch insert natively since 3.7.11
// https://www.sqlite.org/releaselog/3_7_11.html
$this->db->open(); // ensure pdo is not null
if (version_compare($this->db->getServerVersion(), '3.7.11', '>=')) {
return parent::batchInsert($table, $columns, $rows, $params);
}
$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($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) . ') SELECT ' . implode(' UNION SELECT ', $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\Query オブジェクトからSELECT SQL文を生成します。
public array build ( $query, $params = [] ) | ||
$query | yii\db\Query |
SQL文が生成されるyii\db\Queryオブジェクト。 |
$params | array |
生成されたSQL文にバインドされるパラメータ。これらのパラメータは、クエリ構築プロセス中に生成された追加パラメータと共に結果に含まれます。 |
戻り値 | array |
生成されたSQL文(配列の最初の要素)と、SQL文にバインドされる対応するパラメータ(配列の2番目の要素)。返されるパラメータには、 |
---|
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()
2つ以上のSQL式を`AND`または`OR`演算子で接続します。
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);
}
buildCondition()
を使用してください。
定義されている場所: yii\db\QueryBuilder::buildBetweenCondition()
`BETWEEN`演算子を使用したSQL式を作成します。
public string buildBetweenCondition ( $operator, $operands, &$params ) | ||
$operator | string |
使用する演算子(例: |
$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;
}
buildCondition()
を使用してください。
定義されている場所: 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);
}
定義されている場所: yii\db\QueryBuilder::buildFrom()
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);
}
定義されている場所: yii\db\QueryBuilder::buildGroupBy()
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);
}
buildCondition()
を使用してください。
定義されている場所: 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);
}
定義されている場所: yii\db\QueryBuilder::buildHaving()
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;
}
buildCondition()
を使用してください。
定義されている場所: 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);
}
定義されている場所: yii\db\QueryBuilder::buildJoin()
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);
}
buildCondition()
を使用してください。
定義されている場所: 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 = '';
if ($this->hasLimit($limit)) {
$sql = 'LIMIT ' . $limit;
if ($this->hasOffset($offset)) {
$sql .= ' OFFSET ' . $offset;
}
} elseif ($this->hasOffset($offset)) {
// limit is not optional in SQLite
// https://www.sqlite.org/syntaxdiagrams.html#select-stmt
$sql = "LIMIT 9223372036854775807 OFFSET $offset"; // 2^63-1
}
return $sql;
}
buildCondition()
を使用してください。
定義されている場所: 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);
}
定義されている場所: yii\db\QueryBuilder::buildOrderBy()
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;
}
定義されている場所: yii\db\QueryBuilder::buildSelect()
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);
}
buildCondition()
を使用してください。
定義されている場所: 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);
}
定義されている場所: yii\db\QueryBuilder::buildWhere()
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);
}
整合性チェックを有効または無効にします。
public string checkIntegrity ( $check = true, $schema = '', $table = '' ) | ||
$check | boolean |
整合性チェックをオンまたはオフにするかどうか。 |
$schema | string |
テーブルのスキーマ。SQLiteでは無意味。 |
$table | string |
テーブル名。SQLiteでは無意味。 |
戻り値 | string |
整合性チェックのためのSQL文 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function checkIntegrity($check = true, $schema = '', $table = '')
{
return 'PRAGMA foreign_keys=' . (int) $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);
}
新しいインデックスを作成するための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)
{
$tableParts = explode('.', $table);
$schema = null;
if (count($tableParts) === 2) {
list ($schema, $table) = $tableParts;
}
return ($unique ? 'CREATE UNIQUE INDEX ' : 'CREATE INDEX ')
. $this->db->quoteTableName(($schema ? $schema . '.' : '') . $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\sqlite\conditions\LikeConditionBuilder',
'yii\db\conditions\InCondition' => 'yii\db\sqlite\conditions\InConditionBuilder',
]);
}
定義されている場所: 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 |
SQLiteではサポートされていません。 |
public function dropCheck($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
DBカラムを削除するためのSQL文を構築します。
public string dropColumn ( $table, $column ) | ||
$table | string |
カラムを削除するテーブル。このメソッドによって適切に引用符で囲まれます。 |
$column | string |
削除するカラムの名前。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DBカラムを削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function dropColumn($table, $column)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
カラムにコメントを追加するためのSQLコマンドを構築します。
public string dropCommentFromColumn ( $table, $column ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名はメソッドによって適切に引用符で囲まれます。 |
$column | string |
コメントを追加する列の名前。列名はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
列にコメントを追加するためのSQL文 |
---|---|---|
例外 | yii\base\NotSupportedException |
public function dropCommentFromColumn($table, $column)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
テーブルにコメントを追加するためのSQLコマンドを構築します。
public string dropCommentFromTable ( $table ) | ||
$table | string |
コメントを追加する列を持つテーブル。テーブル名はメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
列にコメントを追加するためのSQL文 |
---|---|---|
例外 | yii\base\NotSupportedException |
public function dropCommentFromTable($table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
デフォルト値制約を削除するためのSQLコマンドを作成します。
public string dropDefaultValue ( $name, $table ) | ||
$name | string |
削除するデフォルト値制約の名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
デフォルト値制約を削除するテーブル。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
デフォルト値制約を削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function dropDefaultValue($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
外部キー制約を削除するためのSQL文を構築します。
public string dropForeignKey ( $name, $table ) | ||
$name | string |
削除する外部キー制約の名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
外部キーを削除するテーブル。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
外部キー制約を削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function dropForeignKey($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
インデックスを削除するためのSQL文を構築します。
public string dropIndex ( $name, $table ) | ||
$name | string |
削除するインデックスの名前。このメソッドによって適切に引用符で囲まれます。 |
$table | string |
インデックスを削除するテーブル。このメソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
インデックスを削除するためのSQL文。 |
---|
public function dropIndex($name, $table)
{
return 'DROP INDEX ' . $this->db->quoteTableName($name);
}
既存のテーブルから主キー制約を削除するためのSQL文を構築します。
public string dropPrimaryKey ( $name, $table ) | ||
$name | string |
削除する主キー制約の名前。 |
$table | string |
主キー制約を削除するテーブル。 |
戻り値 | string |
既存のテーブルから主キー制約を削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function dropPrimaryKey($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
定義されている場所: 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);
}
一意制約を削除するためのSQLコマンドを作成します。
public string dropUnique ( $name, $table ) | ||
$name | string |
削除するユニーク制約の名前。メソッドによって適切に引用符で囲まれます。 |
$table | string |
ユニーク制約を削除するテーブル。メソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
ユニーク制約を削除するためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function dropUnique($name, $table)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
定義されている場所: 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 |
基礎となる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
: 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()
指定されたlimitが有効かどうかを確認します。
protected boolean hasLimit ( $limit ) | ||
$limit | mixed |
指定された制限 |
戻り値 | boolean |
制限が有効かどうか |
---|
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()
指定されたoffsetが有効かどうかを確認します。
protected boolean hasOffset ( $offset ) | ||
$offset | mixed |
指定されたオフセット |
戻り値 | boolean |
オフセットが有効かどうか |
---|
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サブクエリとフィールド名を準備します。
protected array prepareInsertSelectSubQuery ( $columns, $schema, $params = [] ) | ||
$columns | yii\db\Query |
selectクエリを表すオブジェクト。 |
$schema | yii\db\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 |
UPDATE SQL文のSET部分の配列(最初の配列要素)とパラメータ(2番目の配列要素)。 |
---|
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)];
}
カラム名を変更するためのSQL文を構築します。
public string renameColumn ( $table, $oldName, $newName ) | ||
$table | string |
カラム名を変更するテーブル。名前はメソッドによって適切に引用符で囲まれます。 |
$oldName | string |
カラムの旧名。名前はメソッドによって適切に引用符で囲まれます。 |
$newName | string |
カラムの新しい名前。メソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DBカラムの名前変更のためのSQL文。 |
---|---|---|
例外 | yii\base\NotSupportedException |
SQLiteではサポートされていません。 |
public function renameColumn($table, $oldName, $newName)
{
throw new NotSupportedException(__METHOD__ . ' is not supported by SQLite.');
}
DBテーブル名を変更するためのSQL文を構築します。
public string renameTable ( $table, $newName ) | ||
$table | string |
名前を変更するテーブル。メソッドによって適切に引用符で囲まれます。 |
$newName | string |
新しいテーブル名。メソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DBテーブルの名前変更のためのSQL文。 |
---|
public function renameTable($table, $newName)
{
return 'ALTER TABLE ' . $this->db->quoteTableName($table) . ' RENAME 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)
{
$db = $this->db;
$table = $db->getTableSchema($tableName);
if ($table !== null && $table->sequenceName !== null) {
$tableName = $db->quoteTableName($tableName);
if ($value === null) {
$key = $this->db->quoteColumnName(reset($table->primaryKey));
$value = $this->db->useMaster(function (Connection $db) use ($key, $tableName) {
return $db->createCommand("SELECT MAX($key) FROM $tableName")->queryScalar();
});
} else {
$value = (int) $value - 1;
}
return "UPDATE sqlite_sequence SET seq='$value' WHERE name='{$table->name}'";
} 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 |
生の形式で選択するサブクエリ。 |
戻り値 | string |
SELECT EXISTS() SQL文。 |
---|
public function selectExists($rawSql)
{
return 'SELECT EXISTS(' . $rawSql . ')';
}
定義済み場所: 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);
}
DBテーブルのデータを削除するためのSQL文を構築します。
public string truncateTable ( $table ) | ||
$table | string |
切り捨てるテーブル。メソッドによって適切に引用符で囲まれます。 |
戻り値 | string |
DBテーブルを切り捨てるためのSQL文。 |
---|
public function truncateTable($table)
{
return 'DELETE FROM ' . $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://stackoverflow.com/questions/15277373/sqlite-upsert-update-or-insert/15277374#15277374.
public string upsert ( $table, $insertColumns, $updateColumns, &$params ) | ||
$table | string |
新しい行が挿入/更新されるテーブル。 |
$insertColumns | array|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;
}
list(, $placeholders, $values, $params) = $this->prepareInsertValues($table, $insertColumns, $params);
$insertSql = 'INSERT OR IGNORE INTO ' . $this->db->quoteTableName($table)
. (!empty($insertNames) ? ' (' . implode(', ', $insertNames) . ')' : '')
. (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : $values);
if ($updateColumns === false) {
return $insertSql;
}
$updateCondition = ['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=(SELECT $quotedName FROM `EXCLUDED`)";
}
$updateCondition[] = $constraintCondition;
}
if ($updateColumns === true) {
$updateColumns = [];
foreach ($updateNames as $name) {
$quotedName = $this->db->quoteColumnName($name);
if (strrpos($quotedName, '.') === false) {
$quotedName = "(SELECT $quotedName FROM `EXCLUDED`)";
}
$updateColumns[$name] = new Expression($quotedName);
}
}
$updateSql = 'WITH "EXCLUDED" (' . implode(', ', $insertNames)
. ') AS (' . (!empty($placeholders) ? 'VALUES (' . implode(', ', $placeholders) . ')' : ltrim($values, ' ')) . ') '
. $this->update($table, $updateColumns, $updateCondition, $params);
return "$updateSql; $insertSql;";
}
コメントするにはサインアップまたはログインしてください。