クラス yii\db\ActiveQuery
ActiveQueryは、アクティブレコードクラスに関連付けられたDBクエリを表します。
ActiveQueryは、通常のクエリまたはリレーショナルコンテキストで使用できます。
ActiveQueryインスタンスは通常、yii\db\ActiveRecord::find()およびyii\db\ActiveRecord::findBySql()によって作成されます。リレーショナルクエリは、yii\db\ActiveRecord::hasOne()およびyii\db\ActiveRecord::hasMany()によって作成されます。
通常のクエリ ¶
ActiveQueryは、主にクエリ結果を取得するために次のメソッドを提供します
- one():データの最初の行が設定された単一のレコードを返します。
- all():クエリ結果に基づいてすべてのレコードを返します。
- count():レコード数を返します。
- sum():指定された列の合計を返します。
- average():指定された列の平均を返します。
- min():指定された列の最小値を返します。
- max():指定された列の最大値を返します。
- scalar():クエリ結果の最初の行の最初の列の値を返します。
- column():クエリ結果の最初の列の値を返します。
- exists():クエリ結果にデータがあるかどうかを示す値を返します。
ActiveQueryはyii\db\Queryから拡張されているため、where()、orderBy()などのクエリメソッドを使用して、クエリオプションをカスタマイズできます。
ActiveQueryは、次の追加のクエリオプションも提供します
- with():このクエリで実行する必要があるリレーションのリスト。
- joinWith():リレーションクエリ定義を再利用して、クエリに結合を追加します。
- indexBy():クエリ結果のインデックスとして使用する列の名前。
- asArray():各レコードを配列として返すかどうか。
これらのオプションは、同じ名前のメソッドを使用して構成できます。例:
$customers = Customer::find()->with('orders')->asArray()->all();
リレーショナルクエリ ¶
リレーショナルコンテキストでは、ActiveQueryは2つのアクティブレコードクラス間のリレーションを表します。
リレーショナルActiveQueryインスタンスは通常、yii\db\ActiveRecord::hasOne()およびyii\db\ActiveRecord::hasMany()を呼び出すことによって作成されます。アクティブレコードクラスは、上記のいずれかのメソッドを呼び出し、作成されたActiveQueryオブジェクトを返すゲッターメソッドを定義することによってリレーションを宣言します。
リレーションは、異なるテーブルの列間の関連を表す$linkによって指定されます。リレーションの多重度は、$multipleによって示されます。
リレーションがジャンクションテーブルを含む場合は、via()またはviaTable()メソッドによって指定できます。これらのメソッドは、リレーショナルコンテキストでのみ呼び出すことができます。同様のことが、リレーションを別のリレーションの逆としてマークするinverseOf()と、リレーショナルクエリ結合条件に追加される条件を追加するonCondition()にも当てはまります。
パブリックプロパティ
パブリックメソッド
メソッド | 説明 | 定義元 |
---|---|---|
__call() | クラスメソッドではない、名前付きのメソッドを呼び出します。 | yii\base\Component |
__clone() | 内部オブジェクトをクローンします。 | yii\db\ActiveRelationTrait |
__construct() | コンストラクタ。 | yii\db\ActiveQuery |
__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 |
alias() | $modelClassで定義されたテーブルのエイリアスを定義します。 | yii\db\ActiveQuery |
all() | クエリを実行し、すべての結果を配列として返します。 | yii\db\ActiveQuery |
andFilterCompare() | 特定の列のフィルタリング条件を追加し、ユーザーがフィルター演算子を選択できるようにします。 | yii\db\Query |
andFilterHaving() | 既存のHAVING条件に追加のHAVING条件を追加しますが、空のオペランドは無視します。 | yii\db\Query |
andFilterWhere() | 既存のWHERE条件に追加のWHERE条件を追加しますが、空のオペランドは無視します。 | yii\db\QueryTrait |
andHaving() | 既存のHAVING条件に追加のHAVING条件を追加します。 | yii\db\Query |
andOnCondition() | 既存のON条件に追加のON条件を追加します。 | yii\db\ActiveQuery |
andWhere() | 既存のWHERE条件に追加のWHERE条件を追加します。 | yii\db\QueryTrait |
asArray() | asArray()プロパティを設定します。 | yii\db\ActiveQueryTrait |
attachBehavior() | このコンポーネントにビヘイビアをアタッチします。 | yii\base\Component |
attachBehaviors() | コンポーネントにビヘイビアのリストをアタッチします。 | yii\base\Component |
average() | 指定された列の値の平均を返します。 | yii\db\Query |
batch() | バッチクエリを開始します。 | yii\db\Query |
behaviors() | このコンポーネントが動作する必要があるビヘイビアのリストを返します。 | yii\base\Component |
cache() | このQueryのクエリキャッシュを有効にします。 | 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\ActiveQuery |
detachBehavior() | コンポーネントからビヘイビアをデタッチします。 | yii\base\Component |
detachBehaviors() | コンポーネントからすべてのビヘイビアをデタッチします。 | yii\base\Component |
distinct() | SELECT DISTINCTを実行するかどうかを示す値を設定します。 | yii\db\Query |
each() | バッチクエリを開始し、データを1行ずつ取得します。 | 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 |
findFor() | 指定されたプライマリレコードの関連レコードを検索します。 | yii\db\ActiveRelationTrait |
findWith() | 1つまたは複数の関係に対応するレコードを検索し、それらをプライマリモデルに設定します。 | yii\db\ActiveQueryTrait |
from() | クエリのFROM部分を設定します。 | yii\db\Query |
getBehavior() | 名前付きのビヘイビアオブジェクトを返します。 | yii\base\Component |
getBehaviors() | このコンポーネントにアタッチされているすべてのビヘイビアを返します。 | yii\base\Component |
getTablesUsedInFrom() | from()で使用されているテーブル名をエイリアスでインデックス付けして返します。 | yii\db\ActiveQuery |
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\db\ActiveQuery |
innerJoin() | クエリにINNER JOIN部分を追加します。 | yii\db\Query |
innerJoinWith() | 指定された関係との内部結合を行います。 | yii\db\ActiveQuery |
inverseOf() | この関係の逆関係である関係の名前を設定します。 | yii\db\ActiveRelationTrait |
join() | クエリにJOIN部分を追加します。 | yii\db\Query |
joinWith() | 指定された関係との結合を行います。 | yii\db\ActiveQuery |
leftJoin() | クエリにLEFT OUTER JOIN部分を追加します。 | yii\db\Query |
limit() | クエリのLIMIT部分を設定します。 | yii\db\QueryTrait |
max() | 指定された列の値の最大値を返します。 | yii\db\Query |
min() | 指定された列の値の最小値を返します。 | yii\db\Query |
noCache() | このQueryのクエリキャッシュを無効にします。 | yii\db\Query |
off() | このコンポーネントから既存のイベントハンドラーをデタッチします。 | yii\base\Component |
offset() | クエリのOFFSET部分を設定します。 | yii\db\QueryTrait |
on() | イベントにイベントハンドラーをアタッチします。 | yii\base\Component |
onCondition() | 関係クエリのON条件を設定します。 | yii\db\ActiveQuery |
one() | クエリを実行し、結果の単一行を返します。 | yii\db\ActiveQuery |
orFilterHaving() | 既存のHAVING条件に追加のHAVING条件を追加しますが、空のオペランドは無視します。 | yii\db\Query |
orFilterWhere() | 既存のWHERE条件に追加のWHERE条件を追加しますが、空のオペランドは無視します。 | yii\db\QueryTrait |
orHaving() | 既存のHAVING条件に追加のHAVING条件を追加します。 | yii\db\Query |
orOnCondition() | 既存のON条件に追加のON条件を追加します。 | yii\db\ActiveQuery |
orWhere() | 既存のWHERE条件に追加のWHERE条件を追加します。 | yii\db\QueryTrait |
orderBy() | クエリのORDER BY部分を設定します。 | yii\db\QueryTrait |
params() | クエリにバインドされるパラメータを設定します。 | yii\db\Query |
populate() | このクエリで指定された形式に、生のクエリ結果を変換します。 | yii\db\ActiveQuery |
populateRelation() | 関連レコードを検索し、それらをプライマリモデルに設定します。 | yii\db\ActiveRelationTrait |
prepare() | SQLを構築するための準備をします。 | yii\db\ActiveQuery |
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 |
via() | ジャンクションテーブルに関連付けられた関係を指定します。 | yii\db\ActiveRelationTrait |
viaTable() | 関係クエリのジャンクションテーブルを指定します。 | yii\db\ActiveQuery |
where() | クエリのWHERE部分を設定します。 | yii\db\QueryTrait |
with() | このクエリを実行する際の関係を指定します。 | yii\db\ActiveQueryTrait |
withQuery() | WITH構文を使用してSQLステートメントを先頭に追加します。 | yii\db\Query |
保護されたメソッド
メソッド | 説明 | 定義元 |
---|---|---|
cleanUpTableNames() | テーブル名とエイリアスをクリーンアップします。エイリアスと名前は両方とも{{と}}で囲まれています。 | yii\db\Query |
createModels() | 検索された行をモデルインスタンスに変換します。 | yii\db\ActiveQueryTrait |
filterCondition() | 指定されたクエリ条件から空のオペランドを削除します。 | yii\db\QueryTrait |
getPrimaryTableName() | yii\db\ActiveQuery | |
getTableNameAndAlias() | $modelClassのテーブル名とテーブルエイリアスを返します。 | yii\db\ActiveQuery |
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\ActiveQuery |
setCommandCache() | このクエリでキャッシングが有効になっている場合、$commandキャッシュを設定します。 | yii\db\Query |
イベント
イベント | タイプ | 説明 | 定義元 |
---|---|---|---|
EVENT_INIT | yii\db\Event | init()を介してクエリが初期化されたときにトリガーされるイベント。 | yii\db\ActiveQuery |
プロパティの詳細
このクエリがリレーショナルコンテキストで使用される場合に適用される結合条件。この条件は、yii\db\ActiveQuery::joinWith() が呼び出されたときに ON 部分で使用されます。それ以外の場合、この条件はクエリの WHERE 部分で使用されます。このパラメータの指定方法については、yii\db\Query::where() を参照してください。
こちらも参照してください:onCondition()。
ARレコードを取得するために実行されるSQLステートメント。これは yii\db\ActiveRecord::findBySql() によって設定されます。
メソッド詳細
定義元: yii\base\Component::__call()
クラスメソッドではない、名前付きのメソッドを呼び出します。
このメソッドは、添付されたビヘイビアに指定された名前のメソッドがあるかどうかを確認し、もしあればそれを実行します。
このメソッドは、不明なメソッドが呼び出されたときに暗黙的に呼び出されるPHPマジックメソッドであるため、直接呼び出さないでください。
public mixed __call ( $name, $params ) | ||
$name | 文字列 |
メソッド名 |
$params | 配列 |
メソッドパラメータ |
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\db\ActiveRelationTrait::__clone()
内部オブジェクトをクローンします。
public void __clone ( ) |
public function __clone()
{
parent::__clone();
// make a clone of "via" object so that the same query object can be reused multiple times
if (is_object($this->via)) {
$this->via = clone $this->via;
} elseif (is_array($this->via)) {
$this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
}
}
コンストラクタ。
public void __construct ( $modelClass, $config = [] ) | ||
$modelClass | 文字列 |
このクエリに関連付けられたモデルクラス |
$config | 配列 |
新しく作成されたクエリオブジェクトに適用される構成 |
public function __construct($modelClass, $config = [])
{
$this->modelClass = $modelClass;
parent::__construct($config);
}
定義元: yii\base\Component::__get()
コンポーネントプロパティの値を返します。
このメソッドは、次の順序でチェックし、それに応じて動作します。
- getterによって定義されたプロパティ:getterの結果を返します
- ビヘイビアのプロパティ:ビヘイビアのプロパティ値を返します
このメソッドは、$value = $component->property;
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください:__set()。
public mixed __get ( $name ) | ||
$name | 文字列 |
プロパティ名 |
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ではないか)を確認します。
このメソッドは、次の順序でチェックし、それに応じて動作します。
- setterによって定義されたプロパティ:プロパティが設定されているかどうかを返します
- ビヘイビアのプロパティ:プロパティが設定されているかどうかを返します
- 存在しないプロパティの場合は
false
を返します
このメソッドは、isset($component->property)
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください:https://www.php.net/manual/en/function.isset.php。
public boolean __isset ( $name ) | ||
$name | 文字列 |
プロパティ名またはイベント名 |
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()
コンポーネントプロパティの値を設定します。
このメソッドは、次の順序でチェックし、それに応じて動作します。
- setterによって定義されたプロパティ:プロパティ値を設定します
- "on xyz"の形式のイベント:イベント"xyz"にハンドラをアタッチします
- "as xyz"の形式のビヘイビア: "xyz"という名前のビヘイビアをアタッチします
- ビヘイビアのプロパティ:ビヘイビアのプロパティ値を設定します
このメソッドは、$component->property = $value;
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください:__get()。
public void __set ( $name, $value ) | ||
$name | 文字列 |
プロパティ名またはイベント名 |
$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);
}
定義元: yii\db\Query::__toString()
QueryのSQL表現を返します。
public string __toString ( ) |
public function __toString()
{
return serialize($this);
}
定義元: yii\base\Component::__unset()
コンポーネントプロパティをnullに設定します。
このメソッドは、次の順序でチェックし、それに応じて動作します。
- setterによって定義されたプロパティ:プロパティ値をnullに設定します
- ビヘイビアのプロパティ:プロパティ値をnullに設定します
このメソッドは、unset($component->property)
を実行するときに暗黙的に呼び出されるPHPマジックメソッドであるため、直接呼び出さないでください。
こちらも参照してください:https://www.php.net/manual/en/function.unset.php。
public void __unset ( $name ) | ||
$name | 文字列 |
プロパティ名 |
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);
}
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;
}
public $this addParams ( $params ) | ||
$params | 配列 |
パラメータープレースホルダーをキーとする、クエリパラメーター値のリスト。たとえば、 |
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;
}
定義元: yii\db\Query::addSelect()
クエリの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()を参照してください。 |
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;
}
$modelClassで定義されたテーブルのエイリアスを定義します。
このメソッドは、すでに定義済みのエイリアスが上書きされるように、from()を調整します。定義されていない場合は、from()に指定されたエイリアスが設定されます。
public $this alias ( $alias ) | ||
$alias | 文字列 |
テーブルエイリアス。 |
return | $this |
クエリオブジェクト自体 |
---|
public function alias($alias)
{
if (empty($this->from) || count($this->from) < 2) {
list($tableName) = $this->getTableNameAndAlias();
$this->from = [$alias => $tableName];
} else {
$tableName = $this->getPrimaryTableName();
foreach ($this->from as $key => $table) {
if ($table === $tableName) {
unset($this->from[$key]);
$this->from[$alias] = $tableName;
}
}
}
return $this;
}
クエリを実行し、すべての結果を配列として返します。
public array|yii\db\ActiveRecord[] all ( $db = null ) | ||
$db | yii\db\Connection|null |
DBコマンドを作成するために使用するDB接続。nullの場合、$modelClassによって返されるDB接続が使用されます。 |
return | array|yii\db\ActiveRecord[] |
クエリ結果。クエリ結果が何もない場合は、空の配列が返されます。 |
---|
public function all($db = null)
{
return parent::all($db);
}
定義元: yii\db\Query::andFilterCompare()
特定の列のフィルタリング条件を追加し、ユーザーがフィルター演算子を選択できるようにします。
指定されたフィールドに追加のWHERE条件を追加し、指定された値の最初の数文字に基づいて比較演算子を決定します。条件はandFilterWhere()と同じ方法で追加されるため、空の値は無視されます。新しい条件と既存の条件は、AND
演算子を使用して結合されます。
比較演算子は、指定された値の最初の数文字に基づいてインテリジェントに決定されます。特に、指定された値の先頭文字として次の演算子を認識します。
<
: 列は指定された値より小さくなければなりません。>
: 列は指定された値より大きくなければなりません。<=
: 列は指定された値以下でなければなりません。>=
: 列は指定された値以上でなければなりません。<>
: 列は指定された値と同じであってはなりません。=
: 列は指定された値と等しくなければなりません。- 上記の演算子が検出されない場合、
$defaultOperator
が使用されます。
public $this andFilterCompare ( $name, $value, $defaultOperator = '=' ) | ||
$name | 文字列 |
列名。 |
$value | 文字列 |
必要に応じて、比較演算子を先頭に付けた列の値。 |
$defaultOperator | 文字列 |
|
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]);
}
定義元: yii\db\Query::andFilterHaving()
既存のHAVING条件に追加のHAVING条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、AND
演算子を使用して結合されます。
このメソッドは、andHaving()に似ています。主な違いは、このメソッドが空のクエリオペランドを削除することです。結果として、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を作成するのに最適です。
関連
public $this andFilterHaving ( array $condition ) | ||
$condition | 配列 |
新しい 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条件に追加のWHERE条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、'AND' 演算子を使って結合されます。
このメソッドは、andWhere() に似ています。主な違いは、このメソッドが 空のクエリ オペランド を削除することです。その結果、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を作成するのに最適です。
関連
public $this andFilterWhere ( array $condition ) | ||
$condition | 配列 |
新しい 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 | 配列 |
クエリにバインドされるパラメーター (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 andOnCondition ( $condition, $params = [] ) | ||
$condition | string|array |
新しい ON 条件です。このパラメーターの指定方法については、where() を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメーター (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andOnCondition($condition, $params = [])
{
if ($this->on === null) {
$this->on = $condition;
} else {
$this->on = ['and', $this->on, $condition];
}
$this->addParams($params);
return $this;
}
定義場所: yii\db\QueryTrait::andWhere()
既存のWHERE条件に追加のWHERE条件を追加します。
新しい条件と既存の条件は、'AND' 演算子を使って結合されます。
関連
public $this andWhere ( $condition ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい WHERE 条件です。このパラメーターの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function andWhere($condition)
{
if ($this->where === null) {
$this->where = $condition;
} else {
$this->where = ['and', $this->where, $condition];
}
return $this;
}
定義場所: yii\db\ActiveQueryTrait::asArray()
asArray()プロパティを設定します。
public $this asArray ( $value = true ) | ||
$value | boolean |
Active Record の代わりに配列でクエリ結果を返すかどうか。 |
return | $this |
クエリオブジェクト自体 |
---|
public function asArray($value = true)
{
$this->asArray = $value;
return $this;
}
定義場所: yii\base\Component::attachBehavior()
このコンポーネントにビヘイビアをアタッチします。
このメソッドは、与えられた構成に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach() メソッドを呼び出すことによって、ビヘイビアオブジェクトはこのコンポーネントにアタッチされます。
また、detachBehavior() も参照してください。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | 文字列 |
ビヘイビアの名前。 |
$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 | 配列 |
コンポーネントにアタッチされるビヘイビアのリスト |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
定義場所: yii\db\Query::average()
指定された列の値の平均を返します。
public mixed average ( $q, $db = null ) | ||
$q | 文字列 |
列名または式。式の中の列名を適切に クォート してください。 |
$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);
}
定義場所: yii\db\Query::batch()
バッチクエリを開始します。
バッチクエリは、メモリ使用量を制限内に抑えながら、データをバッチでフェッチすることをサポートします。このメソッドは、yii\db\BatchQueryResult オブジェクトを返します。これは、Iterator インターフェースを実装しており、バッチでデータを取得するためにトラバースできます。
例:
$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 | 配列 |
ビヘイビアの設定。 |
---|
public function behaviors()
{
return [];
}
このQueryのクエリキャッシュを有効にします。
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 | 文字列 |
プロパティ名 |
$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 | 文字列 |
プロパティ名 |
$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 | 文字列 |
このクラスの完全修飾名。 |
---|
public static function className()
{
return get_called_class();
}
定義元: yii\db\Query::cleanUpTableNames()
テーブル名とエイリアスをクリーンアップします。エイリアスと名前は両方とも{{と}}で囲まれています。
protected string[] cleanUpTableNames ( $tableNames ) | ||
$tableNames | 配列 |
空でない配列 |
return | 文字列[] |
エイリアスでインデックスされたテーブル名 |
---|
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 | 配列 |
クエリ結果の最初の列。クエリの結果が何もない場合は、空の配列が返されます。 |
---|
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 | 文字列 |
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 |
DB コマンドを作成するために使用される DB 接続。 |
return | yii\db\Command |
作成された DB コマンドインスタンス。 |
---|
public function createCommand($db = null)
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
if ($this->sql === null) {
list($sql, $params) = $db->getQueryBuilder()->build($this);
} else {
$sql = $this->sql;
$params = $this->params;
}
$command = $db->createCommand($sql, $params);
$this->setCommandCache($command);
return $command;
}
定義元: yii\db\ActiveQueryTrait::createModels()
検索された行をモデルインスタンスに変換します。
protected array|yii\db\ActiveRecord[] createModels ( $rows ) | ||
$rows | 配列 |
protected function createModels($rows)
{
if ($this->asArray) {
return $rows;
} else {
$models = [];
/* @var $class ActiveRecord */
$class = $this->modelClass;
foreach ($rows as $row) {
$model = $class::instantiate($row);
$modelClass = get_class($model);
$modelClass::populateRecord($model, $row);
$models[] = $model;
}
return $models;
}
}
定義元: yii\base\Component::detachBehavior()
コンポーネントからビヘイビアをデタッチします。
ビヘイビアの yii\base\Behavior::detach() メソッドが呼び出されます。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | 文字列 |
ビヘイビアの名前。 |
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 |
SELECT DISTINCT を行うかどうか。 |
return | $this |
クエリオブジェクト自体 |
---|
public function distinct($value = true)
{
$this->distinct = $value;
return $this;
}
定義元: yii\db\Query::each()
バッチクエリを開始し、データを1行ずつ取得します。
このメソッドは batch() に似ていますが、結果の各イテレーションで、データの1行のみが返される点が異なります。例えば、
$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 | 配列 |
元の条件 |
return | 配列 |
空のオペランドが削除された条件。 |
---|---|---|
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;
}
定義元: yii\db\Query::filterHaving()
クエリの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 | 配列 |
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 | 配列 |
WHERE句に設定されるべき条件。このパラメータの指定方法については、where()を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function filterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->where($condition);
}
return $this;
}
定義場所: yii\db\ActiveRelationTrait::findFor()
指定されたプライマリレコードの関連レコードを検索します。
このメソッドは、ActiveRecord のリレーションが遅延評価でアクセスされるときに呼び出されます。
public mixed findFor ( $name, $model ) | ||
$name | 文字列 |
リレーション名 |
$model | yii\db\ActiveRecordInterface|yii\db\BaseActiveRecord |
プライマリモデル |
return | mixed |
関連レコード(複数可) |
---|---|---|
throws | yii\base\InvalidArgumentException |
リレーションが無効な場合 |
public function findFor($name, $model)
{
if (method_exists($model, 'get' . $name)) {
$method = new \ReflectionMethod($model, 'get' . $name);
$realName = lcfirst(substr($method->getName(), 3));
if ($realName !== $name) {
throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
}
}
return $this->multiple ? $this->all() : $this->one();
}
定義場所: yii\db\ActiveQueryTrait::findWith()
1つまたは複数の関係に対応するレコードを検索し、それらをプライマリモデルに設定します。
public void findWith ( $with, &$models ) | ||
$with | 配列 |
このクエリで実行すべきリレーションのリスト。このパラメータの指定方法の詳細については、with()を参照してください。 |
$models | array|yii\db\ActiveRecord[] |
プライマリモデル(ARインスタンスまたは配列のいずれか) |
public function findWith($with, &$models)
{
if (empty($models)) {
return;
}
$primaryModel = reset($models);
if (!$primaryModel instanceof ActiveRecordInterface) {
/* @var $modelClass ActiveRecordInterface */
$modelClass = $this->modelClass;
$primaryModel = $modelClass::instance();
}
$relations = $this->normalizeRelations($primaryModel, $with);
/* @var $relation ActiveQuery */
foreach ($relations as $name => $relation) {
if ($relation->asArray === null) {
// inherit asArray from primary query
$relation->asArray($this->asArray);
}
$relation->populateRelation($name, $models);
}
}
定義場所: yii\db\Query::from()
クエリのFROM部分を設定します。
public $this from ( $tables ) | ||
$tables | string|array|yii\db\ExpressionInterface |
選択元のテーブル。これは、文字列 (例: テーブルが配列として指定されている場合、配列のキーをテーブルエイリアスとして使用することもできます (テーブルにエイリアスが必要ない場合は、文字列キーを使用しないでください)。 サブクエリを表すには、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 | 文字列 |
ビヘイビア名 |
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;
}
protected string getPrimaryTableName ( ) | ||
return | 文字列 |
プライマリテーブル名 |
---|
protected function getPrimaryTableName()
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
return $modelClass::tableName();
}
$modelClassのテーブル名とテーブルエイリアスを返します。
protected array getTableNameAndAlias ( ) | ||
return | 配列 |
テーブル名とテーブルエイリアス。 |
---|
protected function getTableNameAndAlias()
{
if (empty($this->from)) {
$tableName = $this->getPrimaryTableName();
} else {
$tableName = '';
// if the first entry in "from" is an alias-tablename-pair return it directly
foreach ($this->from as $alias => $tableName) {
if (is_string($alias)) {
return [$tableName, $alias];
}
break;
}
}
if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
$alias = $matches[2];
} else {
$alias = $tableName;
}
return [$tableName, $alias];
}
from()で使用されているテーブル名をエイリアスでインデックス付けして返します。
エイリアスと名前は両方とも {{ と }} で囲まれます。
public string[] getTablesUsedInFrom ( ) | ||
return | 文字列[] |
エイリアスでインデックスされたテーブル名 |
---|---|---|
throws | yii\base\InvalidConfigException |
public function getTablesUsedInFrom()
{
if (empty($this->from)) {
return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
}
return parent::getTablesUsedInFrom();
}
protected array getUnaliasedColumnsFromSelect ( ) | ||
return | 配列 |
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);
}
定義場所: yii\db\Query::getUniqueColumns()
重複を除いた一意の列名を返します。
削除されるカラム
- カラム定義が SELECT 部分に同じエイリアスですでに存在する場合
- エイリアスなしのカラム定義が、エイリアスなしの SELECT 部分にすでにも存在する場合
protected void getUniqueColumns ( $columns ) | ||
$columns | 配列 |
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;
}
public $this groupBy ( $columns ) | ||
$columns | 文字列|配列|yii\db\ExpressionInterface|null |
グループ化に使用するカラム。カラムは文字列(例:"id, name")または配列(例:['id', 'name'])で指定できます。カラムに括弧が含まれない限り(これはカラムがDB式を含むことを意味します)、このメソッドはカラム名を自動的にクォートします。 グループ化がカンマを含む式である場合は、常に配列を使用してグループ化情報を表現する必要があります。そうしないと、このメソッドはグループ化の列を正しく判別できません。 バージョン2.0.7以降、プレーンSQLでGROUP BY句を明示的に指定するために、yii\db\ExpressionInterfaceオブジェクトを渡すことができます。バージョン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 | 文字列 |
イベント名 |
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 | 文字列 |
プロパティ名 |
$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()
このコンポーネントにプロパティが定義されているかどうかを示す値を返します。
プロパティは、以下の場合に定義されます。
- クラスが指定された名前に関連付けられたゲッターまたはセッターメソッドを持っている場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスに指定された名前のメンバー変数がある場合(
$checkVars
が true の場合)。 - アタッチされたビヘイビアが指定された名前のプロパティを持っている場合(
$checkBehaviors
がtrueの場合)。
関連
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 文字列 |
プロパティ名 |
$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 | 配列 |
クエリにバインドされるパラメーター (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 |
クエリ結果のインデックスとして使用するカラムの名前。これは、指定された行データに基づいてインデックス値を返すコールバック(例:匿名関数)にすることもできます。コールバックのシグネチャは次のようになります。
|
return | $this |
クエリオブジェクト自体 |
---|
public function indexBy($column)
{
$this->indexBy = $column;
return $this;
}
オブジェクトを初期化します。
このメソッドはコンストラクタの最後に呼び出されます。デフォルトの実装では、EVENT_INITイベントがトリガーされます。このメソッドをオーバーライドする場合は、イベントのトリガーを確実にするために、最後に親の実装を呼び出すようにしてください。
public void init ( ) |
public function init()
{
parent::init();
$this->trigger(self::EVENT_INIT);
}
定義元: yii\db\Query::innerJoin()
クエリにINNER JOIN部分を追加します。
public $this innerJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには文字列を使用します。テーブル名には、スキーマプレフィックス(例:'public.user')やテーブルエイリアス(例:'user u')を含めることができます。テーブルに括弧が含まれない限り(これはテーブルがサブクエリまたはDB式として与えられていることを意味します)、このメソッドはテーブル名を自動的にクォートします。 テーブルを1つの要素を持つ配列として指定し、配列のキーをテーブルエイリアスとして使用することもできます(例:['u' => 'user'])。 サブクエリを結合するには、値がサブクエリを表すyii\db\Queryオブジェクトに設定された1つの要素を持つ配列を使用し、対応するキーをエイリアスとして使用します。 |
$on | string|array |
ON句に記述する必要がある結合条件。このパラメータの指定方法については、join()を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメーター (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function innerJoin($table, $on = '', $params = [])
{
$this->join[] = ['INNER JOIN', $table, $on];
return $this->addParams($params);
}
指定された関係との内部結合を行います。
これは、結合タイプを「INNER JOIN」に設定したjoinWith()へのショートカットメソッドです。このメソッドの詳細な使用法については、joinWith()を参照してください。
こちらも参照してください joinWith()。
public $this innerJoinWith ( $with, $eagerLoading = true ) | ||
$with | string|array |
結合するリレーション。 |
$eagerLoading | boolean|array |
リレーションをイーガーロードするかどうか。これは、リレーションがクエリ結果から設定されることを意味するものではないことに注意してください。関連データを取得するために、追加のクエリが実行されます。 |
return | $this |
クエリオブジェクト自体 |
---|
public function innerJoinWith($with, $eagerLoading = true)
{
return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
}
定義元: yii\db\ActiveRelationTrait::inverseOf()
この関係の逆関係である関係の名前を設定します。
たとえば、顧客が注文を持っている場合、「注文」リレーションの逆は「顧客」になります。このプロパティが設定されている場合、プライマリレコードは指定されたリレーションを通して参照されます。たとえば、$customer->orders[0]->customer
と$customer
は同じオブジェクトになり、注文の顧客にアクセスしても新しいDBクエリはトリガーされません。
このメソッドは、yii\db\ActiveRecordクラスでリレーションを宣言する際に使用します。例えば、Customerモデルなどです。
public function getOrders()
{
return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
}
Orderモデルにも使用できますが、注意が必要です。
public function getCustomer()
{
return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
}
この場合、結果は注文がどのようにロードされたかによって異なります。顧客が複数の注文を持っていると仮定しましょう。もし1つの注文だけがロードされた場合、
$orders = Order::find()->where(['id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
変数$customerOrders
には1つの注文のみが含まれます。もし注文がこのようにロードされた場合、
$orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
変数$customerOrders
には顧客のすべての注文が含まれます。
public $this inverseOf ( $relationName ) | ||
$relationName | 文字列 |
このリレーションの逆であるリレーションの名前。 |
return | $this |
リレーションオブジェクト自体。 |
---|
public function inverseOf($relationName)
{
$this->inverseOf = $relationName;
return $this;
}
定義元: 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) === '';
}
public $this join ( $type, $table, $on = '', $params = [] ) | ||
$type | 文字列 |
INNER JOIN、LEFT JOINなどの結合タイプ。 |
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには文字列を使用します。テーブル名には、スキーマプレフィックス(例:'public.user')やテーブルエイリアス(例:'user u')を含めることができます。テーブルに括弧が含まれない限り(これはテーブルがサブクエリまたはDB式として与えられていることを意味します)、このメソッドはテーブル名を自動的にクォートします。 テーブルを1つの要素を持つ配列として指定し、配列のキーをテーブルエイリアスとして使用することもできます(例:['u' => 'user'])。 サブクエリを結合するには、値がサブクエリを表すyii\db\Queryオブジェクトに設定された1つの要素を持つ配列を使用し、対応するキーをエイリアスとして使用します。 |
$on | string|array |
ON句に記述されるべき結合条件。このパラメータの指定方法については、where()を参照してください。 where()の配列形式は、列と列を一致させるのではなく、列と値を一致させるように設計されているため、
|
$params | 配列 |
クエリにバインドされるパラメーター (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function join($type, $table, $on = '', $params = [])
{
$this->join[] = [$type, $table, $on];
return $this->addParams($params);
}
指定された関係との結合を行います。
このメソッドは、既存のリレーション定義を再利用してJOINクエリを実行できます。指定されたリレーションの定義に基づいて、このメソッドは現在のクエリに1つ以上のJOINステートメントを追加します。
$eagerLoading
パラメータがtrueの場合、このメソッドは指定されたリレーションに対する遅延ロードも実行します。これは、指定されたリレーションを使用してwith()を呼び出すことと同じです。
JOINクエリが実行されるため、列名を明確にするのはあなたの責任であることに注意してください。
このメソッドは、プライマリテーブルに対してJOIN SQLステートメントを作成して実行するという点で、with()とは異なります。そして、$eagerLoading
がtrueの場合、指定されたリレーションに加えてwith()を呼び出します。
public $this joinWith ( $with, $eagerLoading = true, $joinType = 'LEFT JOIN' ) | ||
$with | string|array |
結合されるリレーション。これは、リレーション名を表す文字列、または以下のセマンティクスを持つ配列のいずれかになります。
リレーション名には、リレーションテーブルのエイリアスを含めることができます(例: サブリレーションも指定できます。構文についてはwith()を参照してください。 以下にいくつかの例を示します。
エイリアス構文はバージョン2.0.7以降で使用できます。 |
$eagerLoading | boolean|array |
|
$joinType | string|array |
|
return | $this |
クエリオブジェクト自体 |
---|
public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
{
$relations = [];
foreach ((array) $with as $name => $callback) {
if (is_int($name)) {
$name = $callback;
$callback = null;
}
if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
// relation is defined with an alias, adjust callback to apply alias
list(, $relation, $alias) = $matches;
$name = $relation;
$callback = function ($query) use ($callback, $alias) {
/* @var $query ActiveQuery */
$query->alias($alias);
if ($callback !== null) {
call_user_func($callback, $query);
}
};
}
if ($callback === null) {
$relations[] = $name;
} else {
$relations[$name] = $callback;
}
}
$this->joinWith[] = [$relations, $eagerLoading, $joinType];
return $this;
}
クエリにLEFT OUTER JOIN部分を追加します。
public $this leftJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには文字列を使用します。テーブル名には、スキーマプレフィックス(例:'public.user')やテーブルエイリアス(例:'user u')を含めることができます。テーブルに括弧が含まれない限り(これはテーブルがサブクエリまたはDB式として与えられていることを意味します)、このメソッドはテーブル名を自動的にクォートします。 テーブルを1つの要素を持つ配列として指定し、配列のキーをテーブルエイリアスとして使用することもできます(例:['u' => 'user'])。 サブクエリを結合するには、値がサブクエリを表すyii\db\Queryオブジェクトに設定された1つの要素を持つ配列を使用し、対応するキーをエイリアスとして使用します。 |
$on | string|array |
ON句に記述する必要がある結合条件。このパラメータの指定方法については、join()を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメータ(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 | 整数|yii\db\ExpressionInterface|null |
制限。制限を無効にするには、nullまたは負の値を使用します。 |
return | $this |
クエリオブジェクト自体 |
---|
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
定義元: yii\db\Query::max()
指定された列の値の最大値を返します。
public mixed max ( $q, $db = null ) | ||
$q | 文字列 |
列名または式。式の中の列名を適切に クォート してください。 |
$db | yii\db\Connection|null |
SQLステートメントを生成するために使用されるデータベース接続。このパラメーターが指定されていない場合、 |
return | mixed |
指定された列の値の最大値。 |
---|
public function max($q, $db = null)
{
return $this->queryScalar("MAX($q)", $db);
}
定義元: yii\db\Query::min()
指定された列の値の最小値を返します。
public mixed min ( $q, $db = null ) | ||
$q | 文字列 |
列名または式。式の中の列名を適切に クォート してください。 |
$db | yii\db\Connection|null |
SQLステートメントを生成するために使用されるデータベース接続。このパラメーターが指定されていない場合、 |
return | mixed |
指定された列の値の最小値。 |
---|
public function min($q, $db = null)
{
return $this->queryScalar("MIN($q)", $db);
}
このQueryのクエリキャッシュを無効にします。
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;
}
定義元: yii\db\Query::normalizeSelect()
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 | 文字列 |
イベント名 |
$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 | 整数|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 | 文字列 |
イベント名 |
$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]);
}
}
関係クエリのON条件を設定します。
この条件は、yii\db\ActiveQuery::joinWith() が呼び出されたときに ON 部分で使用されます。それ以外の場合、この条件はクエリの WHERE 部分で使用されます。
yii\db\ActiveRecord クラスでリレーションを宣言するときに、追加の条件を指定するには、このメソッドを使用します
public function getActiveUsers()
{
return $this->hasMany(User::class, ['id' => 'user_id'])
->onCondition(['active' => true]);
}
この条件は、結合の場合と、関連レコードをフェッチするときにも適用されることに注意してください。したがって、条件で使用できるのは関連テーブルのフィールドのみです。プライマリレコードのフィールドにアクセスしようとすると、非結合クエリでエラーが発生します。
public $this onCondition ( $condition, $params = [] ) | ||
$condition | string|array |
ON条件。このパラメータの指定方法については、yii\db\Query::where() を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメーター (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function onCondition($condition, $params = [])
{
$this->on = $condition;
$this->addParams($params);
return $this;
}
クエリを実行し、結果の単一行を返します。
public yii\db\ActiveRecord|array|null one ( $db = null ) | ||
$db | yii\db\Connection|null |
DB コマンドを作成するために使用される DB 接続。 |
return | yii\db\ActiveRecord|array|null |
クエリ結果の単一行。asArray() の設定によっては、クエリ結果は配列または ActiveRecord オブジェクトになります。クエリ結果が何もなかった場合は、 |
---|
public function one($db = null)
{
$row = parent::one($db);
if ($row !== false) {
$models = $this->populate([$row]);
return reset($models) ?: null;
}
return null;
}
定義元: yii\db\Query::orFilterHaving()
既存のHAVING条件に追加のHAVING条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、OR
演算子を使用して結合されます。
このメソッドは orHaving() に似ています。主な違いは、このメソッドが 空のクエリオペランド を削除することです。その結果、このメソッドは、ユーザーが入力したフィルタ値に基づいてクエリ条件を構築するのに最適です。
関連
public $this orFilterHaving ( array $condition ) | ||
$condition | 配列 |
新しい 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条件に追加のWHERE条件を追加しますが、空のオペランドは無視します。
新しい条件と既存の条件は、'OR'演算子を使って結合されます。
このメソッドはorWhere()に似ています。主な違いは、このメソッドが空のクエリオペランドを削除する点です。そのため、このメソッドはユーザーが入力したフィルター値に基づいてクエリ条件を構築するのに最適です。
関連
public $this orFilterWhere ( array $condition ) | ||
$condition | 配列 |
新しい WHERE 条件です。このパラメーターの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orFilterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->orWhere($condition);
}
return $this;
}
既存のHAVING条件に追加のHAVING条件を追加します。
新しい条件と既存の条件は、OR
演算子を使用して結合されます。
関連
public $this orHaving ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい HAVING 条件です。このパラメーターの指定方法については、where() を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメーター (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 orOnCondition ( $condition, $params = [] ) | ||
$condition | string|array |
新しい ON 条件です。このパラメーターの指定方法については、where() を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメーター (name => value)。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orOnCondition($condition, $params = [])
{
if ($this->on === null) {
$this->on = $condition;
} else {
$this->on = ['or', $this->on, $condition];
}
$this->addParams($params);
return $this;
}
public $this orWhere ( $condition ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新しい WHERE 条件です。このパラメーターの指定方法については、where() を参照してください。 |
return | $this |
クエリオブジェクト自体 |
---|
public function orWhere($condition)
{
if ($this->where === null) {
$this->where = $condition;
} else {
$this->where = ['or', $this->where, $condition];
}
return $this;
}
public $this orderBy ( $columns ) | ||
$columns | 文字列|配列|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;
}
public $this params ( $params ) | ||
$params | 配列 |
パラメータープレースホルダーをキーとする、クエリパラメーター値のリスト。たとえば、 |
return | $this |
クエリオブジェクト自体 |
---|
public function params($params)
{
$this->params = $params;
return $this;
}
このクエリで指定された形式に、生のクエリ結果を変換します。
このメソッドは、データベースからフェッチされたデータを、このクエリで要求される形式に変換するために内部的に使用されます。
public array populate ( $rows ) | ||
$rows | 配列 |
データベースからの未加工のクエリ結果 |
return | 配列 |
変換されたクエリ結果 |
---|
public function populate($rows)
{
if (empty($rows)) {
return [];
}
$models = $this->createModels($rows);
if (!empty($this->join) && $this->indexBy === null) {
$models = $this->removeDuplicatedModels($models);
}
if (!empty($this->with)) {
$this->findWith($this->with, $models);
}
if ($this->inverseOf !== null) {
$this->addInverseRelations($models);
}
if (!$this->asArray) {
foreach ($models as $model) {
$model->afterFind();
}
}
return parent::populate($models);
}
定義元: yii\db\ActiveRelationTrait::populateRelation()
関連レコードを検索し、それらをプライマリモデルに設定します。
public array populateRelation ( $name, &$primaryModels ) | ||
$name | 文字列 |
リレーション名 |
$primaryModels | 配列 |
プライマリモデル |
return | 配列 |
関連モデル |
---|---|---|
throws | yii\base\InvalidConfigException |
$linkが無効な場合 |
public function populateRelation($name, &$primaryModels)
{
if (!is_array($this->link)) {
throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
}
if ($this->via instanceof self) {
// via junction table
/* @var $viaQuery ActiveRelationTrait */
$viaQuery = $this->via;
$viaModels = $viaQuery->findJunctionRows($primaryModels);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->asArray === null) {
// inherit asArray from primary query
$viaQuery->asArray($this->asArray);
}
$viaQuery->primaryModel = null;
$viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
$this->filterByModels($viaModels);
} else {
$this->filterByModels($primaryModels);
}
if (!$this->multiple && count($primaryModels) === 1) {
$model = $this->one();
$primaryModel = reset($primaryModels);
if ($primaryModel instanceof ActiveRecordInterface) {
$primaryModel->populateRelation($name, $model);
} else {
$primaryModels[key($primaryModels)][$name] = $model;
}
if ($this->inverseOf !== null) {
$this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
}
return [$model];
}
// https://github.com/yiisoft/yii2/issues/3197
// delay indexing related models after buckets are built
$indexBy = $this->indexBy;
$this->indexBy = null;
$models = $this->all();
if (isset($viaModels, $viaQuery)) {
$buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
} else {
$buckets = $this->buildBuckets($models, $this->link);
}
$this->indexBy = $indexBy;
if ($this->indexBy !== null && $this->multiple) {
$buckets = $this->indexBuckets($buckets, $this->indexBy);
}
$link = array_values($this->link);
if (isset($viaQuery)) {
$deepViaQuery = $viaQuery;
while ($deepViaQuery->via) {
$deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
};
$link = array_values($deepViaQuery->link);
}
foreach ($primaryModels as $i => $primaryModel) {
$keys = null;
if ($this->multiple && count($link) === 1) {
$primaryModelKey = reset($link);
$keys = isset($primaryModel[$primaryModelKey]) ? $primaryModel[$primaryModelKey] : null;
}
if (is_array($keys)) {
$value = [];
foreach ($keys as $key) {
$key = $this->normalizeModelKey($key);
if (isset($buckets[$key])) {
if ($this->indexBy !== null) {
// if indexBy is set, array_merge will cause renumbering of numeric array
foreach ($buckets[$key] as $bucketKey => $bucketValue) {
$value[$bucketKey] = $bucketValue;
}
} else {
$value = array_merge($value, $buckets[$key]);
}
}
}
} else {
$key = $this->getModelKey($primaryModel, $link);
$value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
}
if ($primaryModel instanceof ActiveRecordInterface) {
$primaryModel->populateRelation($name, $value);
} else {
$primaryModels[$i][$name] = $value;
}
}
if ($this->inverseOf !== null) {
$this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
}
return $models;
}
SQLを構築するための準備をします。
このメソッドは、クエリオブジェクトからSQLの構築を開始する際にyii\db\QueryBuilderによって呼び出されます。クエリをSQLステートメントに変換する際に、最終的な準備作業を行うためにこのメソッドをオーバーライドできます。
public $this prepare ( $builder ) | ||
$builder | yii\db\QueryBuilder | |
return | $this |
yii\db\QueryBuilderがSQLを構築するために使用する準備済みのクエリインスタンス |
---|
public function prepare($builder)
{
// NOTE: because the same ActiveQuery may be used to build different SQL statements
// (e.g. by ActiveDataProvider, one for count query, the other for row data query,
// it is important to make sure the same ActiveQuery can be used to build SQL statements
// multiple times.
if (!empty($this->joinWith)) {
$this->buildJoinWith();
$this->joinWith = null; // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
}
if (empty($this->from)) {
$this->from = [$this->getPrimaryTableName()];
}
if (empty($this->select) && !empty($this->join)) {
list(, $alias) = $this->getTableNameAndAlias();
$this->select = ["$alias.*"];
}
if ($this->primaryModel === null) {
// eager loading
$query = Query::create($this);
} else {
// lazy loading of a relation
$where = $this->where;
if ($this->via instanceof self) {
// via junction table
$viaModels = $this->via->findJunctionRows([$this->primaryModel]);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/* @var $viaQuery ActiveQuery */
list($viaName, $viaQuery, $viaCallableUsed) = $this->via;
if ($viaQuery->multiple) {
if ($viaCallableUsed) {
$viaModels = $viaQuery->all();
} elseif ($this->primaryModel->isRelationPopulated($viaName)) {
$viaModels = $this->primaryModel->$viaName;
} else {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
}
} else {
if ($viaCallableUsed) {
$model = $viaQuery->one();
} elseif ($this->primaryModel->isRelationPopulated($viaName)) {
$model = $this->primaryModel->$viaName;
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
}
$viaModels = $model === null ? [] : [$model];
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
$query = Query::create($this);
$this->where = $where;
}
if (!empty($this->on)) {
$query->andWhere($this->on);
}
return $query;
}
最初に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)
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
if ($db === null) {
$db = $modelClass::getDb();
}
if ($this->sql === null) {
return parent::queryScalar($selectExpression, $db);
}
$command = (new Query())->select([$selectExpression])
->from(['c' => "({$this->sql})"])
->params($this->params)
->createCommand($db);
$this->setCommandCache($command);
return $command->queryScalar();
}
定義元: yii\db\Query::rightJoin()
クエリにRIGHT OUTER JOIN部分を追加します。
public $this rightJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
結合するテーブルまたはサブクエリ。 結合するテーブルの名前を表すには文字列を使用します。テーブル名には、スキーマプレフィックス(例:'public.user')やテーブルエイリアス(例:'user u')を含めることができます。テーブルに括弧が含まれない限り(これはテーブルがサブクエリまたはDB式として与えられていることを意味します)、このメソッドはテーブル名を自動的にクォートします。 テーブルを1つの要素を持つ配列として指定し、配列のキーをテーブルエイリアスとして使用することもできます(例:['u' => 'user'])。 サブクエリを結合するには、値がサブクエリを表すyii\db\Queryオブジェクトに設定された1つの要素を持つ配列を使用し、対応するキーをエイリアスとして使用します。 |
$on | string|array |
ON句に記述する必要がある結合条件。このパラメータの指定方法については、join()を参照してください。 |
$params | 配列 |
クエリにバインドされるパラメータ(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;
}
定義元: yii\db\Query::setCommandCache()
このクエリでキャッシングが有効になっている場合、$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;
}
定義元: yii\db\Query::sum()
指定された列の値の合計を返します。
public mixed sum ( $q, $db = null ) | ||
$q | 文字列 |
列名または式。式の中の列名を適切に クォート してください。 |
$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 | 文字列 |
イベント名 |
$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;
}
定義元: yii\db\ActiveRelationTrait::via()
ジャンクションテーブルに関連付けられた関係を指定します。
yii\db\ActiveRecordクラスでリレーションを宣言するときに、ピボットレコード/テーブルを指定するためにこのメソッドを使用します。
class Order extends ActiveRecord
{
public function getOrderItems() {
return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
}
public function getItems() {
return $this->hasMany(Item::class, ['id' => 'item_id'])
->via('orderItems');
}
}
public $this via ( $relationName, callable $callable = null ) | ||
$relationName | 文字列 |
リレーション名。これは、$primaryModelで宣言されたリレーションを参照します。 |
$callable | callable|null |
ジャンクションテーブルに関連付けられたリレーションをカスタマイズするためのPHPコールバック。そのシグネチャは |
return | $this |
リレーションオブジェクト自体。 |
---|
public function via($relationName, callable $callable = null)
{
$relation = $this->primaryModel->getRelation($relationName);
$callableUsed = $callable !== null;
$this->via = [$relationName, $relation, $callableUsed];
if ($callable !== null) {
call_user_func($callable, $relation);
}
return $this;
}
関係クエリのジャンクションテーブルを指定します。
yii\db\ActiveRecordクラスでリレーションを宣言するときに、ジャンクションテーブルを指定するためにこのメソッドを使用します。
public function getItems()
{
return $this->hasMany(Item::class, ['id' => 'item_id'])
->viaTable('order_item', ['order_id' => 'id']);
}
via()も参照してください。
public $this viaTable ( $tableName, $link, callable $callable = null ) | ||
$tableName | 文字列 |
ジャンクションテーブルの名前。 |
$link | 配列 |
ジャンクションテーブルと$primaryModelに関連付けられたテーブル間のリンク。配列のキーはジャンクションテーブルのカラムを表し、値は$primaryModelテーブルのカラムを表します。 |
$callable | callable|null |
ジャンクションテーブルに関連付けられたリレーションをカスタマイズするためのPHPコールバック。そのシグネチャは |
return | $this |
クエリオブジェクト自体 |
---|---|---|
throws | yii\base\InvalidConfigException |
クエリが正しく初期化されていない場合 |
public function viaTable($tableName, $link, callable $callable = null)
{
$modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass;
$relation = new self($modelClass, [
'from' => [$tableName],
'link' => $link,
'multiple' => true,
'asArray' => true,
]);
$this->via = $relation;
if ($callable !== null) {
call_user_func($callable, $relation);
}
return $this;
}
定義元: yii\db\QueryTrait::where()
クエリのWHERE部分を設定します。
詳細なドキュメントについては、yii\db\QueryInterface::where()を参照してください。
関連
public $this where ( $condition ) | ||
$condition | string|array|yii\db\ExpressionInterface |
WHERE句に配置されるべき条件。 |
return | $this |
クエリオブジェクト自体 |
---|
public function where($condition)
{
$this->where = $condition;
return $this;
}
定義元: yii\db\ActiveQueryTrait::with()
このクエリを実行する際の関係を指定します。
このメソッドへのパラメータは、1つまたは複数の文字列、またはリレーション名と、リレーションをカスタマイズするためのオプションのコールバックの単一の配列のいずれかです。
リレーション名は、$modelClassで定義されたリレーション、または関連レコードのリレーションを表すサブリレーションを参照できます。たとえば、orders.address
は、orders
リレーションに対応するモデルクラスで定義されたaddress
リレーションを意味します。
以下に使用例を示します。
// find customers together with their orders and country
Customer::find()->with('orders', 'country')->all();
// find customers together with their orders and the orders' shipping address
Customer::find()->with('orders.address')->all();
// find customers together with their country and orders of status 1
Customer::find()->with([
'orders' => function (\yii\db\ActiveQuery $query) {
$query->andWhere('status = 1');
},
'country',
])->all();
with()
を複数回呼び出すことができます。各呼び出しは、既存のリレーションに関係を追加します。たとえば、次の2つのステートメントは同等です。
Customer::find()->with('orders', 'country')->all();
Customer::find()->with('orders')->with('country')->all();
public $this with ( ) | ||
return | $this |
クエリオブジェクト自体 |
---|
public function with()
{
$with = func_get_args();
if (isset($with[0]) && is_array($with[0])) {
// the parameter is given as an array
$with = $with[0];
}
if (empty($this->with)) {
$this->with = $with;
} elseif (!empty($with)) {
foreach ($with as $name => $value) {
if (is_int($name)) {
// repeating relation is fine as normalizeRelations() handle it well
$this->with[] = $value;
} else {
$this->with[$name] = $value;
}
}
}
return $this;
}
定義元: yii\db\Query::withQuery()
WITH構文を使用してSQLステートメントを先頭に追加します。
public $this withQuery ( $query, $alias, $recursive = false ) | ||
$query | string|yii\db\Query |
WITHを使用して先頭に追加されるSQLステートメント |
$alias | 文字列 |
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;
}
イベントの詳細
init()を介してクエリが初期化されたときにトリガーされるイベント。
コメントするにはサインアップまたはログインしてください。