Class yii\db\Query
Query は、DBMS に依存しない方法で SELECT SQL ステートメントを表します。
Query は、SELECT ステートメントのさまざまな句の指定を容易にするための一連のメソッドを提供します。これらのメソッドは連鎖させることができます。
createCommand() を呼び出すことで、yii\db\Command インスタンスを取得できます。これは、データベースに対する DB クエリの実行/実行にさらに使用できます。
例:
$query = new Query;
// compose the query
$query->select('id, name')
->from('user')
->limit(10);
// build and execute the query
$rows = $query->all();
// alternatively, you can create DB command and execute it
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();
Query は内部的に yii\db\QueryBuilder クラスを使用して SQL ステートメントを生成します。
Query の使用方法に関する詳細なガイドは、クエリビルダーに関するガイド記事にあります。
公開プロパティ
公開メソッド
メソッド | 説明 | 定義元 |
---|---|---|
__call() | クラスメソッドではない名前付きメソッドを呼び出します。 | yii\base\Component |
__clone() | このメソッドは、既存のオブジェクトを複製してオブジェクトが作成された後に呼び出されます。 | yii\base\Component |
__construct() | コンストラクタ。 | yii\base\BaseObject |
__get() | コンポーネントプロパティの値を返します。 | yii\base\Component |
__isset() | プロパティが設定されているか、つまり定義されていて null でないかを確認します。 | yii\base\Component |
__set() | コンポーネントプロパティの値を設定します。 | yii\base\Component |
__toString() | Query の SQL 表現を返します | yii\db\Query |
__unset() | コンポーネントプロパティを null に設定します。 | yii\base\Component |
addGroupBy() | 既存のグループ化列に追加のグループ化列を追加します。 | yii\db\Query |
addOrderBy() | クエリに追加の ORDER BY 列を追加します。 | yii\db\QueryTrait |
addParams() | クエリにバインドする追加のパラメーターを追加します。 | yii\db\Query |
addSelect() | クエリの SELECT 部分にさらに列を追加します。 | yii\db\Query |
all() | クエリを実行し、すべての結果を配列として返します。 | yii\db\Query |
andFilterCompare() | 特定の列のフィルタリング条件を追加し、ユーザーがフィルター演算子を選択できるようにします。 | yii\db\Query |
andFilterHaving() | 既存の HAVING 条件に追加の HAVING 条件を追加しますが、空のオペランドは無視します。 | yii\db\Query |
andFilterWhere() | 既存の WHERE 条件に条件を追加しますが、空のオペランドは無視します。 | yii\db\QueryTrait |
andHaving() | 既存の HAVING 条件に条件を追加します。 | yii\db\Query |
andWhere() | 既存の WHERE 条件に条件を追加します。 | yii\db\Query |
attachBehavior() | このコンポーネントにビヘイビアをアタッチします。 | yii\base\Component |
attachBehaviors() | コンポーネントにビヘイビアのリストをアタッチします。 | yii\base\Component |
average() | 指定された列の値の平均を返します。 | yii\db\Query |
batch() | バッチクエリを開始します。 | yii\db\Query |
behaviors() | このコンポーネントが振る舞うべきビヘイビアのリストを返します。 | yii\base\Component |
cache() | このクエリのクエリキャッシュを有効にします。 | yii\db\Query |
canGetProperty() | プロパティが読み取り可能かどうかを示す値を返します。 | yii\base\Component |
canSetProperty() | プロパティが設定可能かどうかを示す値を返します。 | yii\base\Component |
className() | このクラスの完全修飾名を返します。 | yii\base\BaseObject |
column() | クエリを実行し、結果の最初の列を返します。 | yii\db\Query |
count() | レコード数を返します。 | yii\db\Query |
create() | 新しい Query オブジェクトを作成し、既存のオブジェクトからプロパティ値をコピーします。 | yii\db\Query |
createCommand() | このクエリの実行に使用できる DB コマンドを作成します。 | yii\db\Query |
detachBehavior() | コンポーネントからビヘイビアをデタッチします。 | yii\base\Component |
detachBehaviors() | コンポーネントからすべてのビヘイビアをデタッチします。 | yii\base\Component |
distinct() | SELECT DISTINCT を行うかどうかを示す値を設定します。 | yii\db\Query |
each() | バッチクエリを開始し、データを行ごとに取得します。 | yii\db\Query |
emulateExecution() | クエリの実行をエミュレートするかどうかを設定し、データストレージとのインタラクションを防ぎます。 | yii\db\QueryTrait |
ensureBehaviors() | behaviors() で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。 | yii\base\Component |
exists() | クエリ結果にデータ行が含まれているかどうかを示す値を返します。 | yii\db\Query |
filterHaving() | クエリの HAVING 部分を設定しますが、空のオペランドは無視します。 | yii\db\Query |
filterWhere() | クエリの WHERE 部分を設定しますが、空のオペランドは無視します。 | yii\db\QueryTrait |
from() | クエリの FROM 部分を設定します。 | yii\db\Query |
getBehavior() | 名前付きビヘイビアオブジェクトを返します。 | yii\base\Component |
getBehaviors() | このコンポーネントにアタッチされているすべてのビヘイビアを返します。 | yii\base\Component |
getTablesUsedInFrom() | from() で使用されているテーブル名をエイリアスでインデックス付けして返します。 | yii\db\Query |
groupBy() | クエリの GROUP BY 部分を設定します。 | yii\db\Query |
hasEventHandlers() | 指定されたイベントにハンドラーがアタッチされているかどうかを示す値を返します。 | yii\base\Component |
hasMethod() | メソッドが定義されているかどうかを示す値を返します。 | yii\base\Component |
hasProperty() | このコンポーネントにプロパティが定義されているかどうかを示す値を返します。 | yii\base\Component |
having() | クエリの HAVING 部分を設定します。 | yii\db\Query |
indexBy() | indexBy() プロパティを設定します。 | yii\db\QueryTrait |
init() | オブジェクトを初期化します。 | yii\base\BaseObject |
innerJoin() | クエリに INNER JOIN 部分を追加します。 | yii\db\Query |
join() | クエリに JOIN 部分を追加します。 | yii\db\Query |
leftJoin() | クエリに LEFT OUTER JOIN 部分を追加します。 | yii\db\Query |
limit() | クエリの LIMIT 部分を設定します。 | yii\db\QueryTrait |
max() | 指定された列の値の最大値を返します。 | yii\db\Query |
min() | 指定された列の値の最小値を返します。 | yii\db\Query |
noCache() | このクエリのクエリキャッシュを無効にします。 | yii\db\Query |
off() | 既存のイベントハンドラーをこのコンポーネントからデタッチします。 | yii\base\Component |
offset() | クエリの OFFSET 部分を設定します。 | yii\db\QueryTrait |
on() | イベントにイベントハンドラーをアタッチします。 | yii\base\Component |
one() | クエリを実行し、結果の単一行を返します。 | yii\db\Query |
orFilterHaving() | 既存の HAVING 条件に追加の HAVING 条件を追加しますが、空のオペランドは無視します。 | yii\db\Query |
orFilterWhere() | 既存の WHERE 条件に条件を追加しますが、空のオペランドは無視します。 | yii\db\QueryTrait |
orHaving() | 既存の HAVING 条件に条件を追加します。 | yii\db\Query |
orWhere() | 既存の WHERE 条件に条件を追加します。 | yii\db\Query |
orderBy() | クエリの ORDER BY 部分を設定します。 | yii\db\QueryTrait |
params() | クエリにバインドされるパラメータを設定します。 | yii\db\Query |
populate() | 生のクエリ結果を、このクエリで指定された形式に変換します。 | yii\db\Query |
prepare() | SQL の構築の準備をします。 | yii\db\Query |
rightJoin() | クエリに RIGHT OUTER JOIN 部分を追加します。 | yii\db\Query |
scalar() | クエリ結果をスカラー値として返します。 | yii\db\Query |
select() | クエリの SELECT 部分を設定します。 | yii\db\Query |
sum() | 指定された列の値の合計を返します。 | yii\db\Query |
trigger() | イベントをトリガーします。 | yii\base\Component |
union() | UNION 演算子を使用して SQL ステートメントを追加します。 | yii\db\Query |
where() | クエリの WHERE 部分を設定します。 | yii\db\Query |
withQuery() | WITH 構文を使用して SQL ステートメントを先頭に追加します。 | yii\db\Query |
保護されたメソッド
メソッド | 説明 | 定義元 |
---|---|---|
cleanUpTableNames() | テーブル名とエイリアスをクリーンアップします。エイリアスと名前は両方とも {{ と }} で囲まれます。 | yii\db\Query |
filterCondition() | 指定されたクエリ条件から 空のオペランド を削除します。 | yii\db\QueryTrait |
getUnaliasedColumnsFromSelect() | yii\db\Query | |
getUniqueColumns() | 重複を除いた一意の列名を返します。 | yii\db\Query |
isEmpty() | 指定された値が「空」かどうかを示す値を返します。 | yii\db\QueryTrait |
normalizeOrderBy() | ORDER BY データの形式を正規化します。 | yii\db\QueryTrait |
normalizeSelect() | select() または addSelect() に渡される SELECT 列を正規化します。 | yii\db\Query |
queryScalar() | 最初に select() を設定して、スカラー値をクエリします。 | yii\db\Query |
setCommandCache() | このクエリでキャッシングが有効になっている場合、$command キャッシュを設定します。 | yii\db\Query |
プロパティの詳細
データの distinct 行のみを選択するかどうか。これが true に設定されている場合、SELECT 句は SELECT DISTINCT に変更されます。
選択元のテーブル。たとえば、['user', 'post']
のように指定します。これは SQL ステートメントの FROM 句を構成するために使用されます。
from() も参照してください。
クエリ結果をグループ化する方法。たとえば、['company', 'department']
のように指定します。これは SQL ステートメントの GROUP BY 句を構成するために使用されます。
GROUP BY 句に適用される条件。文字列または配列のいずれかになります。条件の指定方法については、where() を参照してください。
他のテーブルと結合する方法。各配列要素は、次の構造を持つ 1 つの結合の仕様を表します。
[$joinType, $tableName, $joinCondition]
例:
[
['INNER JOIN', 'user', 'user.id = author_id'],
['LEFT JOIN', 'team', 'team.id = team_id'],
]
クエリパラメータのプレースホルダをキーとした、パラメータ値のリスト。例:[':name' => 'Dan', ':age' => 31]
。
このクエリのキャッシュされたクエリ結果に関連付ける依存関係
以下も参照してください cache()。
クエリ結果がキャッシュ内で有効となるデフォルトの秒数。キャッシュされたデータが期限切れにならないようにする場合は 0 を使用します。クエリキャッシュを使用しない場合は負の数を使用します。 yii\db\Connection::$queryCacheDuration を使用する場合は boolean の true
を使用します。
以下も参照してください cache()。
選択されるカラム。例: ['id', 'name']
。これは SQL ステートメントの SELECT 句を構築するために使用されます。設定されていない場合は、すべてのカラムを選択することを意味します。
以下も参照してください select()。
'SELECT' キーワードに追加される追加のオプション。たとえば、MySQL では、オプション 'SQL_CALC_FOUND_ROWS' を使用できます。
これは SQL ステートメントの UNION 句を構築するために使用されます。各配列要素は、次の構造の配列です。
query
: 文字列またはクエリを表す yii\db\Query オブジェクトのいずれかall
: boolean。UNION ALL
かUNION
かを指定
これは SQL クエリの WITH セクションを構築するために使用されます。各配列要素は、次の構造の配列です。
query
: 文字列またはクエリを表す yii\db\Query オブジェクトのいずれかalias
: 文字列。後で使用するためのクエリのエイリアスrecursive
: boolean。WITH RECURSIVE
かWITH
かを指定
以下も参照してください withQuery()。
メソッド詳細
定義: yii\base\Component::__call()
クラスメソッドではない名前付きメソッドを呼び出します。
このメソッドは、アタッチされたビヘイビアに指定されたメソッドがあるかどうかを確認し、利用可能な場合は実行します。
このメソッドは、不明なメソッドが呼び出されたときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
public mixed __call ( $name, $params ) | ||
$name | string |
メソッド名 |
$params | array |
メソッドのパラメータ |
return | mixed |
メソッドの戻り値 |
---|---|---|
throws | yii\base\UnknownMethodException |
不明なメソッドを呼び出したとき |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
定義: yii\base\Component::__clone()
このメソッドは、既存のオブジェクトを複製してオブジェクトが作成された後に呼び出されます。
古いオブジェクトにアタッチされているため、すべてのビヘイビアを削除します。
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
定義: yii\base\BaseObject::__construct()
コンストラクタ。
デフォルトの実装では、次の2つのことを行います。
- 指定された構成
$config
でオブジェクトを初期化します。 - init() を呼び出します。
このメソッドが子クラスでオーバーライドされる場合、次のことが推奨されます。
- コンストラクタの最後のパラメータは、ここでの
$config
のような構成配列です。 - コンストラクタの最後に、親の実装を呼び出します。
public void __construct ( $config = [] ) | ||
$config | array |
オブジェクトのプロパティを初期化するために使用される名前と値のペア |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
定義: yii\base\Component::__get()
コンポーネントプロパティの値を返します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- getter によって定義されたプロパティ: getter の結果を返します
- ビヘイビアのプロパティ: ビヘイビアのプロパティ値を返します
このメソッドは、$value = $component->property;
を実行するときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください __set()。
public mixed __get ( $name ) | ||
$name | string |
プロパティ名 |
return | mixed |
プロパティの値、またはビヘイビアのプロパティの値 |
---|---|---|
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
throws | yii\base\InvalidCallException |
プロパティが書き込み専用の場合。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (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\Component::__isset()
プロパティが設定されているか、つまり定義されていて null でないかを確認します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターによって定義されたプロパティ: プロパティが設定されているかどうかを返します
- ビヘイビアのプロパティ: プロパティが設定されているかどうかを返します
- 存在しないプロパティについては
false
を返します
このメソッドは、isset($component->property)
を実行するときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください https://www.php.net/manual/en/function.isset.php。
public boolean __isset ( $name ) | ||
$name | string |
プロパティ名またはイベント名 |
return | boolean |
指定されたプロパティが設定されているかどうか |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
定義元: yii\base\Component::__set()
コンポーネントプロパティの値を設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターによって定義されたプロパティ: プロパティ値を設定します
- "on xyz" の形式のイベント: イベント "xyz" にハンドラーをアタッチします
- "as xyz" の形式のビヘイビア: "xyz" という名前のビヘイビアをアタッチします
- ビヘイビアのプロパティ: ビヘイビアのプロパティ値を設定します
このメソッドは、$component->property = $value;
を実行するときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください __get()。
public void __set ( $name, $value ) | ||
$name | string |
プロパティ名またはイベント名 |
$value | mixed |
プロパティ値 |
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
---|---|---|
throws | yii\base\InvalidCallException |
プロパティが読み取り専用の場合。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
Query の SQL 表現を返します
public string __toString ( ) |
public function __toString()
{
return serialize($this);
}
定義元: yii\base\Component::__unset()
コンポーネントプロパティを null に設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターによって定義されたプロパティ: プロパティ値を null に設定します
- ビヘイビアのプロパティ: プロパティ値を null に設定します
このメソッドは、unset($component->property)
を実行するときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください https://www.php.net/manual/en/function.unset.php。
public void __unset ( $name ) | ||
$name | string |
プロパティ名 |
throws | yii\base\InvalidCallException |
プロパティが読み取り専用の場合。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
既存のグループ化列に追加のグループ化列を追加します。
こちらも参照してください groupBy()。
public $this addGroupBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface |
グループ化する追加の列。列は文字列 (例: "id, name") または配列 (例: ['id', 'name']) のいずれかで指定できます。メソッドは、列に括弧が含まれている場合 (つまり、列に DB 式が含まれている場合) を除き、自動的に列名をクォートします。 グループ化がカンマを含む式である場合は、常に配列を使用してグループ化情報を表す必要があります。そうしないと、メソッドはグループ化列を正しく判別できません。 バージョン 2.0.7 以降、yii\db\Expression オブジェクトを渡して、GROUP BY 部分をプレーン SQL で明示的に指定できます。バージョン 2.0.14 以降、yii\db\ExpressionInterface オブジェクトも渡すことができます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function addGroupBy($columns)
{
if ($columns instanceof ExpressionInterface) {
$columns = [$columns];
} elseif (!is_array($columns)) {
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
}
if ($this->groupBy === null) {
$this->groupBy = $columns;
} else {
$this->groupBy = array_merge($this->groupBy, $columns);
}
return $this;
}
public $this addOrderBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface |
並べ替える列 (および方向)。列は文字列 (例: "id ASC, name DESC") または配列 (例: メソッドは、列に括弧が含まれている場合 (つまり、列に DB 式が含まれている場合) を除き、自動的に列名をクォートします。 順序がカンマを含む式である場合は、常に配列を使用して順序情報を表す必要があります。そうしないと、メソッドは順序列を正しく判別できません。 バージョン 2.0.7 以降、yii\db\ExpressionInterface オブジェクトを渡して、ORDER BY 部分をプレーン SQL で明示的に指定できます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function addOrderBy($columns)
{
$columns = $this->normalizeOrderBy($columns);
if ($this->orderBy === null) {
$this->orderBy = $columns;
} else {
$this->orderBy = array_merge($this->orderBy, $columns);
}
return $this;
}
クエリにバインドする追加のパラメーターを追加します。
こちらも参照してください params()。
public $this addParams ( $params ) | ||
$params | array |
クエリパラメータのプレースホルダをキーとした、パラメータ値のリスト。例: |
return | $this |
クエリオブジェクト自体 |
---|
public function addParams($params)
{
if (!empty($params)) {
if (empty($this->params)) {
$this->params = $params;
} else {
foreach ($params as $name => $value) {
if (is_int($name)) {
$this->params[] = $value;
} else {
$this->params[$name] = $value;
}
}
}
}
return $this;
}
クエリの SELECT 部分にさらに列を追加します。
select() が以前に指定されていない場合、残りのすべての列も選択する場合は、明示的に *
を含める必要があることに注意してください
$query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
以下も参照してください select()。
public $this addSelect ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface |
select に追加する列。このパラメーターの形式の詳細については、select() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function addSelect($columns)
{
if ($this->select === null) {
return $this->select($columns);
}
if (!is_array($this->select)) {
$this->select = $this->normalizeSelect($this->select);
}
$this->select = array_merge($this->select, $this->normalizeSelect($columns));
return $this;
}
クエリを実行し、すべての結果を配列として返します。
public array all ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | array |
クエリ結果。クエリの結果が何もない場合は、空の配列が返されます。 |
---|
public function all($db = null)
{
if ($this->emulateExecution) {
return [];
}
$rows = $this->createCommand($db)->queryAll();
return $this->populate($rows);
}
特定の列のフィルタリング条件を追加し、ユーザーがフィルター演算子を選択できるようにします。
指定されたフィールドに対して追加の WHERE 条件を追加し、指定された値の最初の数文字に基づいて比較演算子を決定します。条件は andFilterWhere() と同じ方法で追加されるため、空の値 は無視されます。新しい条件と既存の条件は AND
演算子を使用して結合されます。
比較演算子は、指定された値の最初の数文字に基づいてインテリジェントに決定されます。特に、与えられた値の先頭文字として現れる場合、以下の演算子を認識します。
<
: 列の値が指定された値より小さい必要があります。>
: 列の値が指定された値より大きい必要があります。<=
: 列の値が指定された値以下である必要があります。>=
: 列の値が指定された値以上である必要があります。<>
: 列の値が指定された値と同じであってはなりません。=
: 列の値が指定された値と等しい必要があります。- 上記の演算子が検出されない場合、
$defaultOperator
が使用されます。
public $this andFilterCompare ( $name, $value, $defaultOperator = '=' ) | ||
$name | string |
列名。 |
$value | string |
必要に応じて比較演算子を前に付けた列の値。 |
$defaultOperator | string |
|
return | $this |
クエリオブジェクト自体 |
---|
public function andFilterCompare($name, $value, $defaultOperator = '=')
{
if (preg_match('/^(<>|>=|>|<=|<|=)/', (string)$value, $matches)) {
$operator = $matches[1];
$value = substr($value, strlen($operator));
} else {
$operator = $defaultOperator;
}
return $this->andFilterWhere([$operator, $name, $value]);
}
既存の HAVING 条件に追加の HAVING 条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は AND
演算子を使用して結合されます。
このメソッドは andHaving() に似ています。主な違いは、このメソッドが 空のクエリオペランド を削除することです。その結果、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を構築するのに最適です。
参照
public $this andFilterHaving ( array $condition ) | ||
$condition | array |
新しい HAVING 条件。このパラメータの指定方法については、having() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andFilterHaving(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->andHaving($condition);
}
return $this;
}
定義場所: yii\db\QueryTrait::andFilterWhere()
既存の WHERE 条件に条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は 'AND' 演算子を使用して結合されます。
このメソッドは andWhere() に似ています。主な違いは、このメソッドが 空のクエリオペランド を削除することです。その結果、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を構築するのに最適です。
参照
public $this andFilterWhere ( array $condition ) | ||
$condition | array |
新しい WHERE 条件。このパラメータの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andFilterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->andWhere($condition);
}
return $this;
}
public $this andHaving ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい HAVING 条件。このパラメータの指定方法については、where() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andHaving($condition, $params = [])
{
if ($this->having === null) {
$this->having = $condition;
} else {
$this->having = ['and', $this->having, $condition];
}
$this->addParams($params);
return $this;
}
public $this andWhere ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい WHERE 条件。このパラメータの指定方法については、where() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andWhere($condition, $params = [])
{
if ($this->where === null) {
$this->where = $condition;
} elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
$this->where[] = $condition;
} else {
$this->where = ['and', $this->where, $condition];
}
$this->addParams($params);
return $this;
}
定義場所: yii\base\Component::attachBehavior()
このコンポーネントにビヘイビアをアタッチします。
このメソッドは、指定された構成に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach() メソッドを呼び出して、ビヘイビアオブジェクトをこのコンポーネントにアタッチします。
detachBehavior() も参照してください。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
ビヘイビアの名前。 |
$behavior | string|array|yii\base\Behavior |
ビヘイビアの構成。これは次のいずれかになります。
|
return | yii\base\Behavior |
ビヘイビアオブジェクト |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義場所: yii\base\Component::attachBehaviors()
コンポーネントにビヘイビアのリストをアタッチします。
各ビヘイビアは名前でインデックス付けされており、yii\base\Behavior オブジェクト、ビヘイビアクラスを指定する文字列、またはビヘイビアを作成するための構成配列である必要があります。
attachBehavior() も参照してください。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
コンポーネントにアタッチされるビヘイビアのリスト |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
指定された列の値の平均を返します。
public mixed average ( $q, $db = null ) | ||
$q | string |
列名または式。式中の列名を適切にクォートしてください。 |
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | mixed |
指定された列の値の平均。 |
---|
public function average($q, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("AVG($q)", $db);
}
バッチクエリを開始します。
バッチクエリは、メモリ使用量を制限内に保つことができるバッチでのデータフェッチをサポートします。このメソッドは、Iterator インターフェースを実装し、バッチでデータを取得するためにトラバースできる yii\db\BatchQueryResult オブジェクトを返します。
例:
$query = (new Query)->from('user');
foreach ($query->batch() as $rows) {
// $rows is an array of 100 or fewer rows from user table
}
public yii\db\BatchQueryResult batch ( $batchSize = 100, $db = null ) | ||
$batchSize | 整数 |
各バッチでフェッチされるレコード数。 |
$db | yii\db\Connection|null |
データベース接続。設定されていない場合は、「db」アプリケーションコンポーネントが使用されます。 |
return | yii\db\BatchQueryResult |
バッチクエリの結果です。これはIteratorインターフェースを実装しており、データをバッチで取得するためにトラバースできます。 |
---|
public function batch($batchSize = 100, $db = null)
{
return Yii::createObject([
'class' => BatchQueryResult::className(),
'query' => $this,
'batchSize' => $batchSize,
'db' => $db,
'each' => false,
]);
}
定義元: yii\base\Component::behaviors()
このコンポーネントが振る舞うべきビヘイビアのリストを返します。
子クラスは、動作させたいビヘイビアを指定するために、このメソッドをオーバーライドできます。
このメソッドの戻り値は、ビヘイビア名でインデックス付けされたビヘイビアオブジェクトまたは構成の配列である必要があります。ビヘイビア構成は、ビヘイビアクラスを指定する文字列、または次の構造の配列のいずれかになります。
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
ビヘイビアクラスは、yii\base\Behaviorから拡張する必要があることに注意してください。ビヘイビアは、名前を使用するか、匿名でアタッチできます。名前が配列キーとして使用されている場合、この名前を使用して、ビヘイビアは後でgetBehavior()を使用して取得するか、detachBehavior()を使用してデタッチできます。匿名のビヘイビアは、取得またはデタッチできません。
このメソッドで宣言されたビヘイビアは、コンポーネントに自動的に(必要に応じて)アタッチされます。
public array behaviors ( ) | ||
return | array |
ビヘイビア構成。 |
---|
public function behaviors()
{
return [];
}
このクエリのクエリキャッシュを有効にします。
public $this cache ( $duration = true, $dependency = null ) | ||
$duration | integer|true |
クエリ結果がキャッシュ内で有効な秒数。キャッシュされたデータが期限切れにならないようにするには0を使用します。クエリキャッシュを使用しないことを示すには負の数を使用します。yii\db\Connection::$queryCacheDurationを使用することを示すには、ブール値 |
$dependency | yii\caching\Dependency|null |
キャッシュされた結果に関連付けられたキャッシュの依存関係。 |
return | $this |
Queryオブジェクト自体 |
---|
public function cache($duration = true, $dependency = null)
{
$this->queryCacheDuration = $duration;
$this->queryCacheDependency = $dependency;
return $this;
}
定義元: yii\base\Component::canGetProperty()
プロパティが読み取り可能かどうかを示す値を返します。
プロパティは、以下の場合に読み取ることができます。
- クラスに指定された名前に関連付けられたゲッターメソッドがある場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスに指定された名前のメンバー変数がある場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアに、指定された名前の読み取り可能なプロパティがある場合(
$checkBehaviors
がtrueの場合)。
canSetProperty()も参照してください。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバー変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが読み取り可能かどうか |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
定義元: yii\base\Component::canSetProperty()
プロパティが設定可能かどうかを示す値を返します。
プロパティは、以下の場合に書き込むことができます。
- クラスに指定された名前に関連付けられたセッターメソッドがある場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスに指定された名前のメンバー変数がある場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアに、指定された名前の書き込み可能なプロパティがある場合(
$checkBehaviors
がtrueの場合)。
canGetProperty()も参照してください。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバー変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが書き込み可能かどうか |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
を使用してください。
定義元: yii\base\BaseObject::className()
このクラスの完全修飾名を返します。
public static string className ( ) | ||
return | string |
このクラスの完全修飾名。 |
---|
public static function className()
{
return get_called_class();
}
テーブル名とエイリアスをクリーンアップします。エイリアスと名前は両方とも {{ と }} で囲まれます。
protected string[] cleanUpTableNames ( $tableNames ) | ||
$tableNames | array |
空ではない配列 |
return | string[] |
エイリアスでインデックス付けされたテーブル名 |
---|
protected function cleanUpTableNames($tableNames)
{
$cleanedUpTableNames = [];
foreach ($tableNames as $alias => $tableName) {
if (is_string($tableName) && !is_string($alias)) {
$pattern = <<<PATTERN
'"`\[]|{{)
'"`\]]|}})
?\)
\s+
(?:as)?
\s*
?:['"`\[]|{{)
.*?
(?:['"`\]]|}})
|
.*?
ERN;
if (preg_match($pattern, $tableName, $matches)) {
if (isset($matches[2])) {
list(, $tableName, $alias) = $matches;
} else {
$tableName = $alias = $matches[1];
}
}
}
if ($tableName instanceof Expression) {
if (!is_string($alias)) {
throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
}
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
} elseif ($tableName instanceof self) {
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
} else {
$cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
}
}
return $cleanedUpTableNames;
}
クエリを実行し、結果の最初の列を返します。
public array column ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | array |
クエリ結果の最初の列。クエリの結果が何もなければ、空の配列が返されます。 |
---|
public function column($db = null)
{
if ($this->emulateExecution) {
return [];
}
if ($this->indexBy === null) {
return $this->createCommand($db)->queryColumn();
}
if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
$this->select[] = key($tables) . '.' . $this->indexBy;
} else {
$this->select[] = $this->indexBy;
}
}
$rows = $this->createCommand($db)->queryAll();
$results = [];
$column = null;
if (is_string($this->indexBy)) {
if (($dotPos = strpos($this->indexBy, '.')) === false) {
$column = $this->indexBy;
} else {
$column = substr($this->indexBy, $dotPos + 1);
}
}
foreach ($rows as $row) {
$value = reset($row);
if ($this->indexBy instanceof \Closure) {
$results[call_user_func($this->indexBy, $row)] = $value;
} else {
$results[$row[$column]] = $value;
}
}
return $results;
}
レコード数を返します。
public integer|string|null count ( $q = '*', $db = null ) | ||
$q | string |
COUNT式。デフォルトは '*' です。式の中で列名を適切に引用符で囲むことを確認してください。 |
$db | yii\db\Connection|null |
SQLステートメントの生成に使用するデータベース接続。このパラメータが指定されていない(またはnull)場合、 |
return | integer|string|null |
レコード数。結果は、基盤となるデータベースエンジンに応じて文字列になる場合があり、32ビットPHP整数が処理できるよりも高い整数値をサポートするためです。 |
---|
public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("COUNT($q)", $db);
}
新しい Query オブジェクトを作成し、既存のオブジェクトからプロパティ値をコピーします。
コピーされるプロパティは、クエリビルダーで使用されるものです。
public static yii\db\Query create ( $from ) | ||
$from | yii\db\Query |
ソースクエリオブジェクト |
return | yii\db\Query |
新しい Query オブジェクト |
---|
public static function create($from)
{
return new self([
'where' => $from->where,
'limit' => $from->limit,
'offset' => $from->offset,
'orderBy' => $from->orderBy,
'indexBy' => $from->indexBy,
'select' => $from->select,
'selectOption' => $from->selectOption,
'distinct' => $from->distinct,
'from' => $from->from,
'groupBy' => $from->groupBy,
'join' => $from->join,
'having' => $from->having,
'union' => $from->union,
'params' => $from->params,
'withQueries' => $from->withQueries,
]);
}
このクエリの実行に使用できる DB コマンドを作成します。
public yii\db\Command createCommand ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | yii\db\Command |
作成されたDBコマンドインスタンス。 |
---|
public function createCommand($db = null)
{
if ($db === null) {
$db = Yii::$app->getDb();
}
list($sql, $params) = $db->getQueryBuilder()->build($this);
$command = $db->createCommand($sql, $params);
$this->setCommandCache($command);
return $command;
}
定義元: yii\base\Component::detachBehavior()
コンポーネントからビヘイビアをデタッチします。
ビヘイビアの yii\base\Behavior::detach() メソッドが呼び出されます。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
ビヘイビアの名前。 |
return | yii\base\Behavior|null |
デタッチされたビヘイビア。ビヘイビアが存在しない場合は Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
定義元: yii\base\Component::detachBehaviors()
コンポーネントからすべてのビヘイビアをデタッチします。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
SELECT DISTINCT を行うかどうかを示す値を設定します。
public $this distinct ( $value = true ) | ||
$value | boolean |
DISTINCT を SELECT するかどうか。 |
return | $this |
クエリオブジェクト自体 |
---|
public function distinct($value = true)
{
$this->distinct = $value;
return $this;
}
バッチクエリを開始し、データを行ごとに取得します。
このメソッドは、結果の各イテレーションで1行のデータのみが返される点を除いて、batch() と似ています。たとえば、
$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}
public yii\db\BatchQueryResult each ( $batchSize = 100, $db = null ) | ||
$batchSize | 整数 |
各バッチでフェッチされるレコード数。 |
$db | yii\db\Connection|null |
データベース接続。設定されていない場合は、「db」アプリケーションコンポーネントが使用されます。 |
return | yii\db\BatchQueryResult |
バッチクエリの結果です。これはIteratorインターフェースを実装しており、データをバッチで取得するためにトラバースできます。 |
---|
public function each($batchSize = 100, $db = null)
{
return Yii::createObject([
'class' => BatchQueryResult::className(),
'query' => $this,
'batchSize' => $batchSize,
'db' => $db,
'each' => true,
]);
}
定義元: yii\db\QueryTrait::emulateExecution()
クエリの実行をエミュレートするかどうかを設定し、データストレージとのインタラクションを防ぎます。
このモードが有効になると、yii\db\QueryInterface::one()、yii\db\QueryInterface::all()、yii\db\QueryInterface::exists()などのクエリ結果を返すメソッドは、空または false の値を返します。このメソッドは、0=1
のような false の where 条件を設定した場合など、プログラムロジックがクエリが結果を返さないことを示す場合に使う必要があります。
public $this emulateExecution ( $value = true ) | ||
$value | boolean |
クエリの実行を阻止するかどうか。 |
return | $this |
クエリオブジェクト自体。 |
---|
public function emulateExecution($value = true)
{
$this->emulateExecution = $value;
return $this;
}
定義元: yii\base\Component::ensureBehaviors()
behaviors() で宣言されたビヘイビアがこのコンポーネントにアタッチされていることを確認します。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
クエリ結果にデータ行が含まれているかどうかを示す値を返します。
public boolean exists ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | boolean |
クエリの結果にデータ行が含まれているかどうか。 |
---|
public function exists($db = null)
{
if ($this->emulateExecution) {
return false;
}
$command = $this->createCommand($db);
$params = $command->params;
$command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
$command->bindValues($params);
return (bool) $command->queryScalar();
}
定義元: yii\db\QueryTrait::filterCondition()
指定されたクエリ条件から 空のオペランド を削除します。
protected array filterCondition ( $condition ) | ||
$condition | array |
元の条件 |
return | array |
空のオペランド が削除された条件。 |
---|---|---|
throws | yii\base\NotSupportedException |
条件演算子がサポートされていない場合 |
protected function filterCondition($condition)
{
if (!is_array($condition)) {
return $condition;
}
if (!isset($condition[0])) {
// hash format: 'column1' => 'value1', 'column2' => 'value2', ...
foreach ($condition as $name => $value) {
if ($this->isEmpty($value)) {
unset($condition[$name]);
}
}
return $condition;
}
// operator format: operator, operand 1, operand 2, ...
$operator = array_shift($condition);
switch (strtoupper($operator)) {
case 'NOT':
case 'AND':
case 'OR':
foreach ($condition as $i => $operand) {
$subCondition = $this->filterCondition($operand);
if ($this->isEmpty($subCondition)) {
unset($condition[$i]);
} else {
$condition[$i] = $subCondition;
}
}
if (empty($condition)) {
return [];
}
break;
case 'BETWEEN':
case 'NOT BETWEEN':
if (array_key_exists(1, $condition) && array_key_exists(2, $condition)) {
if ($this->isEmpty($condition[1]) || $this->isEmpty($condition[2])) {
return [];
}
}
break;
default:
if (array_key_exists(1, $condition) && $this->isEmpty($condition[1])) {
return [];
}
}
array_unshift($condition, $operator);
return $condition;
}
クエリの HAVING 部分を設定しますが、空のオペランドは無視します。
このメソッドは having() と似ています。主な違いは、このメソッドが 空のクエリオペランド を削除することです。結果として、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を作成するのに最適です。
次のコードは、このメソッドと having() の違いを示しています。
// HAVING `age`=:age
$query->filterHaving(['name' => null, 'age' => 20]);
// HAVING `age`=:age
$query->having(['age' => 20]);
// HAVING `name` IS NULL AND `age`=:age
$query->having(['name' => null, 'age' => 20]);
having() とは異なり、このメソッドにバインドパラメーターを渡すことはできません。
参照
public $this filterHaving ( array $condition ) | ||
$condition | array |
HAVING 部分に入れる必要のある条件。このパラメーターの指定方法については、having() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function filterHaving(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->having($condition);
}
return $this;
}
定義元: yii\db\QueryTrait::filterWhere()
クエリの WHERE 部分を設定しますが、空のオペランドは無視します。
このメソッドは where() と似ています。主な違いは、このメソッドが 空のクエリオペランド を削除することです。結果として、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を作成するのに最適です。
次のコードは、このメソッドと where() の違いを示しています。
// WHERE `age`=:age
$query->filterWhere(['name' => null, 'age' => 20]);
// WHERE `age`=:age
$query->where(['age' => 20]);
// WHERE `name` IS NULL AND `age`=:age
$query->where(['name' => null, 'age' => 20]);
where() とは異なり、このメソッドにバインドパラメーターを渡すことはできません。
参照
public $this filterWhere ( array $condition ) | ||
$condition | array |
WHERE 部分に入れる必要のある条件。このパラメーターの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function filterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->where($condition);
}
return $this;
}
クエリの FROM 部分を設定します。
public $this from ( $tables ) | ||
$tables | string|array|yii\db\ExpressionInterface |
選択元のテーブル(複数可)。これは、1つまたは複数のテーブル名を指定する文字列(例: テーブルが配列として指定されている場合、配列のキーをテーブルエイリアスとして使用することもできます(テーブルにエイリアスが必要ない場合は、文字列キーを使用しないでください)。 サブクエリを表すには、Queryオブジェクトを使用します。この場合、対応する配列キーがサブクエリのエイリアスとして使用されます。 プレーンSQLで 以下にいくつかの例を示します
|
return | $this |
クエリオブジェクト自体 |
---|
public function from($tables)
{
if ($tables instanceof ExpressionInterface) {
$tables = [$tables];
}
if (is_string($tables)) {
$tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
}
$this->from = $tables;
return $this;
}
定義元: yii\base\Component::getBehavior()
名前付きビヘイビアオブジェクトを返します。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
ビヘイビアの名前 |
return | yii\base\Behavior|null |
ビヘイビアオブジェクト。存在しない場合は null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義元: yii\base\Component::getBehaviors()
このコンポーネントにアタッチされているすべてのビヘイビアを返します。
public yii\base\Behavior[] getBehaviors ( ) | ||
return | yii\base\Behavior[] |
このコンポーネントにアタッチされたビヘイビアのリスト |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
from() で使用されているテーブル名をエイリアスでインデックス付けして返します。
エイリアスと名前は両方とも{{と}}で囲まれています。
public string[] getTablesUsedInFrom ( ) | ||
return | string[] |
エイリアスでインデックス付けされたテーブル名 |
---|---|---|
throws | yii\base\InvalidConfigException |
public function getTablesUsedInFrom()
{
if (empty($this->from)) {
return [];
}
if (is_array($this->from)) {
$tableNames = $this->from;
} elseif (is_string($this->from)) {
$tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
} elseif ($this->from instanceof Expression) {
$tableNames = [$this->from];
} else {
throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
}
return $this->cleanUpTableNames($tableNames);
}
protected array getUnaliasedColumnsFromSelect ( ) | ||
return | array |
SELECTステートメントからのエイリアスなしの列のリスト。 |
---|
protected function getUnaliasedColumnsFromSelect()
{
$result = [];
if (is_array($this->select)) {
foreach ($this->select as $name => $value) {
if (is_int($name)) {
$result[] = $value;
}
}
}
return array_unique($result);
}
重複を除いた一意の列名を返します。
削除する列
- 同じエイリアスでSELECT部分に列定義が既に存在する場合
- エイリアスなしの列定義がSELECT部分にエイリアスなしで既に存在する場合
protected void getUniqueColumns ( $columns ) | ||
$columns | array |
selectにマージする列。 |
protected function getUniqueColumns($columns)
{
$unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
$result = [];
foreach ($columns as $columnAlias => $columnDefinition) {
if (!$columnDefinition instanceof Query) {
if (is_string($columnAlias)) {
$existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
if ($existsInSelect) {
continue;
}
} elseif (is_int($columnAlias)) {
$existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
$existsInResultSet = in_array($columnDefinition, $result, true);
if ($existsInSelect || $existsInResultSet) {
continue;
}
}
}
$result[$columnAlias] = $columnDefinition;
}
return $result;
}
クエリの GROUP BY 部分を設定します。
参考: addGroupBy().
public $this groupBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface|null |
グループ化する列。列は、文字列(例: "id, name")または配列(例: ['id', 'name'])のいずれかで指定できます。メソッドは、列が括弧を含む場合(これは列がDB式を含むことを意味します)を除き、自動的に列名をクォートします。 グループ化がカンマを含む式である場合は、常に配列を使用してグループ化情報を表す必要があります。そうしないと、メソッドはグループ化列を正しく判別できません。 バージョン2.0.7以降、yii\db\ExpressionInterfaceオブジェクトを渡して、GROUP BY部分をプレーンSQLで明示的に指定できます。バージョン2.0.14以降、yii\db\ExpressionInterfaceオブジェクトを渡すこともできます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function groupBy($columns)
{
if ($columns instanceof ExpressionInterface) {
$columns = [$columns];
} elseif (!is_array($columns) && !is_null($columns)) {
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
}
$this->groupBy = $columns;
return $this;
}
定義元: yii\base\Component::hasEventHandlers()
指定されたイベントにハンドラーがアタッチされているかどうかを示す値を返します。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
イベント名 |
return | boolean |
イベントにハンドラがアタッチされているかどうか。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義元: yii\base\Component::hasMethod()
メソッドが定義されているかどうかを示す値を返します。
メソッドが定義されている場合
- クラスが指定された名前のメソッドを持つ場合
- アタッチされたビヘイビアが指定された名前のメソッドを持つ場合(
$checkBehaviors
がtrueの場合)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkBehaviors | boolean |
ビヘイビアのメソッドをこのコンポーネントのメソッドとして扱うかどうか |
return | boolean |
メソッドが定義されているかどうか |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義元: yii\base\Component::hasProperty()
このコンポーネントにプロパティが定義されているかどうかを示す値を返します。
プロパティが定義されている場合
- クラスが指定された名前に関連付けられたgetterまたはsetterメソッドを持つ場合(この場合、プロパティ名は大文字と小文字を区別しません)。
- クラスに指定された名前のメンバー変数がある場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアが指定された名前のプロパティを持つ場合(
$checkBehaviors
がtrueの場合)。
参照
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバー変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | boolean |
プロパティが定義されているかどうか |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
public $this having ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
HAVINGの後に置く条件。このパラメータの指定方法については、where()を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function having($condition, $params = [])
{
$this->having = $condition;
$this->addParams($params);
return $this;
}
定義元: yii\db\QueryTrait::indexBy()
indexBy() プロパティを設定します。
public $this indexBy ( $column ) | ||
$column | string|callable |
クエリ結果のインデックスとして使用するカラム名。または、与えられた行データに基づいてインデックス値を返す callable (例: 無名関数) も指定できます。callable のシグネチャは次のようである必要があります。
|
return | $this |
クエリオブジェクト自体 |
---|
public function indexBy($column)
{
$this->indexBy = $column;
return $this;
}
public void init ( ) |
public function init()
{
}
クエリに INNER JOIN 部分を追加します。
public $this innerJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには、文字列を使用します。テーブル名には、スキーマプレフィックス (例: 'public.user') やテーブルエイリアス (例: 'user u') を含めることができます。テーブルがサブクエリまたは DB 式として指定されていることを意味する括弧が含まれていない限り、メソッドは自動的にテーブル名をクォートします。 テーブルを 1 つの要素を持つ配列として指定することもできます。この場合、配列キーをテーブルエイリアスとして使用します (例: ['u' => 'user'])。 サブクエリを結合するには、1 つの要素を持つ配列を使用します。この場合、値はサブクエリを表す yii\db\Query オブジェクトに設定し、対応するキーをエイリアスとして設定します。 |
$on | string|array |
ON 部分に表示される結合条件。このパラメータの指定方法については、join() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function innerJoin($table, $on = '', $params = [])
{
$this->join[] = ['INNER JOIN', $table, $on];
return $this->addParams($params);
}
定義元: yii\db\QueryTrait::isEmpty()
指定された値が「空」かどうかを示す値を返します。
値が次のいずれかの条件を満たす場合、「空」と見なされます。
null
である、- 空の文字列 (
''
) である、 - 空白文字のみを含む文字列である、
- または空の配列である。
protected boolean isEmpty ( $value ) | ||
$value | mixed | |
return | boolean |
値が空の場合 |
---|
protected function isEmpty($value)
{
return $value === '' || $value === [] || $value === null || is_string($value) && trim($value) === '';
}
クエリに JOIN 部分を追加します。
最初のパラメータは、結合の種類を指定します。
public $this join ( $type, $table, $on = '', $params = [] ) | ||
$type | string |
INNER JOIN、LEFT JOIN などの結合の種類。 |
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには、文字列を使用します。テーブル名には、スキーマプレフィックス (例: 'public.user') やテーブルエイリアス (例: 'user u') を含めることができます。テーブルがサブクエリまたは DB 式として指定されていることを意味する括弧が含まれていない限り、メソッドは自動的にテーブル名をクォートします。 テーブルを 1 つの要素を持つ配列として指定することもできます。この場合、配列キーをテーブルエイリアスとして使用します (例: ['u' => 'user'])。 サブクエリを結合するには、1 つの要素を持つ配列を使用します。この場合、値はサブクエリを表す yii\db\Query オブジェクトに設定し、対応するキーをエイリアスとして設定します。 |
$on | string|array |
ON 部分に表示される結合条件。このパラメータの指定方法については、where() を参照してください。 where() の配列形式は、列と値を対応させるように設計されており、列と列を対応させるようには設計されていないため、次の例は期待どおりに機能しません:
|
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function join($type, $table, $on = '', $params = [])
{
$this->join[] = [$type, $table, $on];
return $this->addParams($params);
}
クエリに LEFT OUTER JOIN 部分を追加します。
public $this leftJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには、文字列を使用します。テーブル名には、スキーマプレフィックス (例: 'public.user') やテーブルエイリアス (例: 'user u') を含めることができます。テーブルがサブクエリまたは DB 式として指定されていることを意味する括弧が含まれていない限り、メソッドは自動的にテーブル名をクォートします。 テーブルを 1 つの要素を持つ配列として指定することもできます。この場合、配列キーをテーブルエイリアスとして使用します (例: ['u' => 'user'])。 サブクエリを結合するには、1 つの要素を持つ配列を使用します。この場合、値はサブクエリを表す yii\db\Query オブジェクトに設定し、対応するキーをエイリアスとして設定します。 |
$on | string|array |
ON 部分に表示される結合条件。このパラメータの指定方法については、join() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function leftJoin($table, $on = '', $params = [])
{
$this->join[] = ['LEFT JOIN', $table, $on];
return $this->addParams($params);
}
定義元: yii\db\QueryTrait::limit()
クエリの LIMIT 部分を設定します。
public $this limit ( $limit ) | ||
$limit | integer|yii\db\ExpressionInterface|null |
制限。制限を無効にするには、null または負の値を使用します。 |
return | $this |
クエリオブジェクト自体 |
---|
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
指定された列の値の最大値を返します。
public mixed max ( $q, $db = null ) | ||
$q | string |
列名または式。式中の列名を適切にクォートしてください。 |
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | mixed |
指定された列の値の最大値。 |
---|
public function max($q, $db = null)
{
return $this->queryScalar("MAX($q)", $db);
}
指定された列の値の最小値を返します。
public mixed min ( $q, $db = null ) | ||
$q | string |
列名または式。式中の列名を適切にクォートしてください。 |
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | mixed |
指定された列の値の最小値。 |
---|
public function min($q, $db = null)
{
return $this->queryScalar("MIN($q)", $db);
}
このクエリのクエリキャッシュを無効にします。
public $this noCache ( ) | ||
return | $this |
Queryオブジェクト自体 |
---|
public function noCache()
{
$this->queryCacheDuration = -1;
return $this;
}
定義元: yii\db\QueryTrait::normalizeOrderBy()
ORDER BY データの形式を正規化します。
protected array normalizeOrderBy ( $columns ) | ||
$columns | array|string|yii\db\ExpressionInterface|null |
正規化する列の値。orderBy() および addOrderBy() を参照してください。 |
protected function normalizeOrderBy($columns)
{
if (empty($columns)) {
return [];
} elseif ($columns instanceof ExpressionInterface) {
return [$columns];
} elseif (is_array($columns)) {
return $columns;
}
$columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
$result = [];
foreach ($columns as $column) {
if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
$result[$matches[1]] = strcasecmp($matches[2], 'desc') ? SORT_ASC : SORT_DESC;
} else {
$result[$column] = SORT_ASC;
}
}
return $result;
}
select() または addSelect() に渡される SELECT 列を正規化します。
protected array normalizeSelect ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface |
protected function normalizeSelect($columns)
{
if ($columns instanceof ExpressionInterface) {
$columns = [$columns];
} elseif (!is_array($columns)) {
$columns = preg_split('/\s*,\s*/', trim((string)$columns), -1, PREG_SPLIT_NO_EMPTY);
}
$select = [];
foreach ($columns as $columnAlias => $columnDefinition) {
if (is_string($columnAlias)) {
// Already in the normalized format, good for them
$select[$columnAlias] = $columnDefinition;
continue;
}
if (is_string($columnDefinition)) {
if (
preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
!preg_match('/^\d+$/', $matches[2]) &&
strpos($matches[2], '.') === false
) {
// Using "columnName as alias" or "columnName alias" syntax
$select[$matches[2]] = $matches[1];
continue;
}
if (strpos($columnDefinition, '(') === false) {
// Normal column name, just alias it to itself to ensure it's not selected twice
$select[$columnDefinition] = $columnDefinition;
continue;
}
}
// Either a string calling a function, DB expression, or sub-query
$select[] = $columnDefinition;
}
return $select;
}
定義元: yii\base\Component::off()
既存のイベントハンドラーをこのコンポーネントからデタッチします。
このメソッドは、on() の反対です。
注意: イベント名にワイルドカードパターンが渡された場合、そのワイルドカードで登録されたハンドラのみが削除され、そのワイルドカードに一致するプレーンな名前で登録されたハンドラは残ります。
こちらも参照してください: on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
イベント名 |
$handler | callable|null |
削除するイベントハンドラ。null の場合、指定されたイベントにアタッチされたすべてのハンドラが削除されます。 |
return | boolean |
ハンドラが見つかり、デタッチされた場合 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
定義元: yii\db\QueryTrait::offset()
クエリの OFFSET 部分を設定します。
public $this offset ( $offset ) | ||
$offset | integer|yii\db\ExpressionInterface|null |
オフセット。オフセットを無効にするには、null または負の値を使用します。 |
return | $this |
クエリオブジェクト自体 |
---|
public function offset($offset)
{
$this->offset = $offset;
return $this;
}
イベントにイベントハンドラーをアタッチします。
イベントハンドラは、有効な PHP コールバックである必要があります。以下にいくつかの例を示します。
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
イベントハンドラは、次のシグネチャで定義する必要があります。
function ($event)
ここで、$event
は、イベントに関連付けられたパラメータを含む yii\base\Event オブジェクトです。
2.0.14 以降、イベント名をワイルドカードパターンとして指定できます。
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
こちらも参照してください: off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
イベント名 |
$handler | callable |
イベントハンドラ |
$data | mixed |
イベントがトリガーされたときにイベントハンドラに渡されるデータ。イベントハンドラが呼び出されると、このデータは yii\base\Event::$data を介してアクセスできます。 |
$append | boolean |
既存のハンドラリストの末尾に新しいイベントハンドラを追加するかどうか。false の場合、新しいハンドラは既存のハンドラリストの先頭に挿入されます。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
クエリを実行し、結果の単一行を返します。
public array|boolean one ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | array|boolean |
クエリ結果の最初の行 (配列の形式)。クエリ結果が何もない場合は False が返されます。 |
---|
public function one($db = null)
{
if ($this->emulateExecution) {
return false;
}
return $this->createCommand($db)->queryOne();
}
既存の HAVING 条件に追加の HAVING 条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、OR
演算子を使用して結合されます。
このメソッドは、orHaving() と似ています。主な違いは、このメソッドは 空のクエリオペランド を削除することです。その結果、このメソッドは、ユーザーが入力したフィルタ値に基づいてクエリ条件を作成するのに最適です。
参照
public $this orFilterHaving ( array $condition ) | ||
$condition | array |
新しい HAVING 条件。このパラメータの指定方法については、having() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orFilterHaving(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->orHaving($condition);
}
return $this;
}
定義元: yii\db\QueryTrait::orFilterWhere()
既存の WHERE 条件に条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、'OR' 演算子を使用して結合されます。
このメソッドは、orWhere() と似ています。主な違いは、このメソッドは 空のクエリオペランド を削除することです。その結果、このメソッドは、ユーザーが入力したフィルタ値に基づいてクエリ条件を作成するのに最適です。
参照
public $this orFilterWhere ( array $condition ) | ||
$condition | array |
新しい WHERE 条件。このパラメータの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orFilterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->orWhere($condition);
}
return $this;
}
public $this orHaving ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい HAVING 条件。このパラメータの指定方法については、where() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orHaving($condition, $params = [])
{
if ($this->having === null) {
$this->having = $condition;
} else {
$this->having = ['or', $this->having, $condition];
}
$this->addParams($params);
return $this;
}
public $this orWhere ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい WHERE 条件。このパラメータの指定方法については、where() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orWhere($condition, $params = [])
{
if ($this->where === null) {
$this->where = $condition;
} else {
$this->where = ['or', $this->where, $condition];
}
$this->addParams($params);
return $this;
}
public $this orderBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface|null |
並べ替える列(と方向)。列は、文字列(例: メソッドは、列に括弧が含まれている場合 (つまり、列に DB 式が含まれている場合) を除き、自動的に列名をクォートします。 順序がカンマを含む式である場合は、常に配列を使用して順序情報を表す必要があります。そうしないと、メソッドは順序列を正しく判別できません。 バージョン 2.0.7 以降、yii\db\ExpressionInterface オブジェクトを渡して、ORDER BY 部分をプレーン SQL で明示的に指定できます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orderBy($columns)
{
$this->orderBy = $this->normalizeOrderBy($columns);
return $this;
}
クエリにバインドされるパラメータを設定します。
こちらも参照してください: addParams()。
public $this params ( $params ) | ||
$params | array |
クエリパラメータのプレースホルダをキーとした、パラメータ値のリスト。例: |
return | $this |
クエリオブジェクト自体 |
---|
public function params($params)
{
$this->params = $params;
return $this;
}
生のクエリ結果を、このクエリで指定された形式に変換します。
このメソッドは、データベースからフェッチされたデータを、このクエリで要求される形式に変換するために内部的に使用されます。
public array populate ( $rows ) | ||
$rows | array |
データベースからの生のクエリ結果 |
return | array |
変換されたクエリ結果 |
---|
public function populate($rows)
{
if ($this->indexBy === null) {
return $rows;
}
$result = [];
foreach ($rows as $row) {
$result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
}
return $result;
}
SQL の構築の準備をします。
このメソッドは、クエリオブジェクトからSQLの構築を開始するときに、yii\db\QueryBuilderによって呼び出されます。クエリをSQLステートメントに変換する際の最終的な準備作業を行うために、このメソッドをオーバーライドできます。
public $this prepare ( $builder ) | ||
$builder | yii\db\QueryBuilder | |
return | $this |
yii\db\QueryBuilderがSQLを構築するために使用する準備されたクエリインスタンス |
---|
public function prepare($builder)
{
return $this;
}
最初に select() を設定して、スカラー値をクエリします。
このクエリを再利用可能にするために、selectの値を復元します。
protected boolean|string|null queryScalar ( $selectExpression, $db ) | ||
$selectExpression | string|yii\db\ExpressionInterface | |
$db | yii\db\Connection|null |
クエリの実行に使用されるデータベース接続。 |
throws | Throwable |
コマンドを作成できない場合 |
---|
protected function queryScalar($selectExpression, $db)
{
if ($this->emulateExecution) {
return null;
}
if (
!$this->distinct
&& empty($this->groupBy)
&& empty($this->having)
&& empty($this->union)
) {
$select = $this->select;
$order = $this->orderBy;
$limit = $this->limit;
$offset = $this->offset;
$this->select = [$selectExpression];
$this->orderBy = null;
$this->limit = null;
$this->offset = null;
$e = null;
try {
$command = $this->createCommand($db);
} catch (\Exception $e) {
// throw it later (for PHP < 7.0)
} catch (\Throwable $e) {
// throw it later
}
$this->select = $select;
$this->orderBy = $order;
$this->limit = $limit;
$this->offset = $offset;
if ($e !== null) {
throw $e;
}
return $command->queryScalar();
}
$command = (new self())
->select([$selectExpression])
->from(['c' => $this])
->createCommand($db);
$this->setCommandCache($command);
return $command->queryScalar();
}
クエリに RIGHT OUTER JOIN 部分を追加します。
public $this rightJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには、文字列を使用します。テーブル名には、スキーマプレフィックス (例: 'public.user') やテーブルエイリアス (例: 'user u') を含めることができます。テーブルがサブクエリまたは DB 式として指定されていることを意味する括弧が含まれていない限り、メソッドは自動的にテーブル名をクォートします。 テーブルを 1 つの要素を持つ配列として指定することもできます。この場合、配列キーをテーブルエイリアスとして使用します (例: ['u' => 'user'])。 サブクエリを結合するには、1 つの要素を持つ配列を使用します。この場合、値はサブクエリを表す yii\db\Query オブジェクトに設定し、対応するキーをエイリアスとして設定します。 |
$on | string|array |
ON 部分に表示される結合条件。このパラメータの指定方法については、join() を参照してください。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function rightJoin($table, $on = '', $params = [])
{
$this->join[] = ['RIGHT JOIN', $table, $on];
return $this->addParams($params);
}
クエリ結果をスカラー値として返します。
返される値は、クエリ結果の最初の行の最初の列になります。
public string|integer|null|false scalar ( $db = null ) | ||
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | string|integer|null|false |
クエリ結果の最初の行の最初の列の値。クエリ結果が空の場合はfalseが返されます。 |
---|
public function scalar($db = null)
{
if ($this->emulateExecution) {
return null;
}
return $this->createCommand($db)->queryScalar();
}
クエリの SELECT 部分を設定します。
public $this select ( $columns, $option = null ) | ||
$columns | string|array|yii\db\ExpressionInterface |
選択する列。列は、文字列(例: "id, name")または配列(例:['id'、'name'])のいずれかで指定できます。列にはテーブル名(例: "user.id")をプレフィックスとして付けることができ、列エイリアス(例: "user.id AS user_id")を含めることもできます。列に括弧が含まれている場合(これは列にDB式が含まれていることを意味します)、メソッドは自動的に列名を引用符で囲みます。DB式は、yii\db\ExpressionInterfaceオブジェクトの形式で渡すこともできます。
列が配列として指定されている場合、配列キーを列エイリアスとして使用することもできます(列にエイリアスが必要ない場合は、文字列キーを使用しないでください)。 バージョン2.0.1以降では、サブクエリを表す |
$option | string|null |
'SELECT' キーワードに追加される追加のオプション。たとえば、MySQL では、オプション 'SQL_CALC_FOUND_ROWS' を使用できます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function select($columns, $option = null)
{
$this->select = $this->normalizeSelect($columns);
$this->selectOption = $option;
return $this;
}
このクエリでキャッシングが有効になっている場合、$command キャッシュを設定します。
protected yii\db\Command setCommandCache ( $command ) | ||
$command | yii\db\Command |
protected function setCommandCache($command)
{
if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
$duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
$command->cache($duration, $this->queryCacheDependency);
}
return $command;
}
指定された列の値の合計を返します。
public mixed sum ( $q, $db = null ) | ||
$q | string |
列名または式。式中の列名を適切にクォートしてください。 |
$db | yii\db\Connection|null |
SQL ステートメントの生成に使用されるデータベース接続。このパラメーターが指定されていない場合は、 |
return | mixed |
指定された列の値の合計。 |
---|
public function sum($q, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("SUM($q)", $db);
}
定義: yii\base\Component::trigger()
イベントをトリガーします。
このメソッドは、イベントの発生を表します。クラスレベルのハンドラーを含む、イベントに添付されたすべてのハンドラーを呼び出します。
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
イベント名 |
$event | yii\base\Event|null |
イベントインスタンス。設定されていない場合は、デフォルトのyii\base\Eventオブジェクトが作成されます。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
UNION 演算子を使用して SQL ステートメントを追加します。
public $this union ( $sql, $all = false ) | ||
$sql | string|yii\db\Query |
UNIONを使用して追加されるSQLステートメント |
$all | boolean |
UNION ALLを使用する場合はTRUE、UNIONを使用する場合はFALSE |
return | $this |
クエリオブジェクト自体 |
---|
public function union($sql, $all = false)
{
$this->union[] = ['query' => $sql, 'all' => $all];
return $this;
}
クエリの WHERE 部分を設定します。
このメソッドには、$condition
パラメーターと、必要に応じて、クエリにバインドする値を指定する$params
パラメーターが必要です。
$condition
パラメーターは、文字列(例:'id=1'
)または配列のいずれかである必要があります。
{@inheritdoc}
参照
public $this where ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
WHERE部分に配置する必要がある条件。 |
$params | array |
クエリにバインドされるパラメータ (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function where($condition, $params = [])
{
$this->where = $condition;
$this->addParams($params);
return $this;
}
WITH 構文を使用して SQL ステートメントを先頭に追加します。
public $this withQuery ( $query, $alias, $recursive = false ) | ||
$query | string|yii\db\Query |
WITHを使用して先頭に追加されるSQLステートメント |
$alias | string |
WITH構成におけるクエリエイリアス |
$recursive | boolean |
WITH RECURSIVEを使用する場合はTRUE、WITHを使用する場合はFALSE |
return | $this |
クエリオブジェクト自体 |
---|
public function withQuery($query, $alias, $recursive = false)
{
$this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive];
return $this;
}
サインアップまたはログインしてコメントしてください。