2 追蹤者

抽象類別 yii\db\BaseActiveRecord

繼承yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject
實作ArrayAccessIteratorAggregateyii\base\Arrayableyii\base\Configurableyii\base\StaticInstanceInterfaceyii\db\ActiveRecordInterface
使用 Traitsyii\base\ArrayableTraityii\base\StaticInstanceTrait
子類別yii\db\ActiveRecord
可用版本自2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php

ActiveRecord 是代表物件形式的關聯式資料之類別的基礎類別。

請參閱 yii\db\ActiveRecord 以取得具體實作。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$activeValidators yii\validators\Validator[] 適用於目前 $scenario 的驗證器。 yii\base\Model
$attributes array 屬性值 (name => value)。 yii\base\Model
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$dirtyAttributes array 已變更的屬性值(名稱-值對)。 yii\db\BaseActiveRecord
$errors array 所有屬性或指定屬性的錯誤。 yii\base\Model
$firstErrors array 第一個錯誤。 yii\base\Model
$isNewRecord boolean 記錄是否為新的,且在呼叫 save() 時應插入。 yii\db\BaseActiveRecord
$iterator ArrayIterator 用於遍歷列表中項目的迭代器。 yii\base\Model
$oldAttributes array 舊的屬性值(名稱-值對)。 yii\db\BaseActiveRecord
$oldPrimaryKey mixed 舊的主鍵值。 yii\db\BaseActiveRecord
$primaryKey mixed 主鍵值。 yii\db\BaseActiveRecord
$relatedRecords array 依關聯名稱索引的關聯記錄陣列。 yii\db\BaseActiveRecord
$scenario string 此模型的場景。 yii\base\Model
$validators ArrayObject|yii\validators\Validator[] 模型中宣告的所有驗證器。 yii\base\Model

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫非類別方法的具名方法。 yii\base\Component
__clone() 在透過複製現有物件建立物件後,會呼叫此方法。 yii\base\Model
__construct() 建構子。 yii\base\BaseObject
__get() PHP getter 魔術方法。 yii\db\BaseActiveRecord
__isset() 檢查屬性值是否為 null。 yii\db\BaseActiveRecord
__set() PHP setter 魔術方法。 yii\db\BaseActiveRecord
__unset() 將元件屬性設定為 null。 yii\db\BaseActiveRecord
activeAttributes() 傳回目前情境中需要驗證的屬性名稱。 yii\base\Model
addError() 將新錯誤新增至指定的屬性。 yii\base\Model
addErrors() 新增錯誤列表。 yii\base\Model
afterDelete() 刪除記錄後會調用此方法。 yii\db\BaseActiveRecord
afterFind() 當建立 AR 物件並使用查詢結果填入時,會呼叫此方法。 yii\db\BaseActiveRecord
afterRefresh() 重新整理 AR 物件時會呼叫此方法。 yii\db\BaseActiveRecord
afterSave() 在插入或更新記錄結束時會呼叫此方法。 yii\db\BaseActiveRecord
afterValidate() 驗證結束後會調用此方法。 yii\base\Model
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
attributeHints() 傳回屬性提示。 yii\base\Model
attributeLabels() 傳回屬性標籤。 yii\base\Model
attributes() 傳回屬性名稱列表。 yii\base\Model
beforeDelete() 刪除記錄之前會調用此方法。 yii\db\BaseActiveRecord
beforeSave() 在插入或更新記錄開始時會呼叫此方法。 yii\db\BaseActiveRecord
beforeValidate() 驗證開始之前會調用此方法。 yii\base\Model
behaviors() 傳回此元件應表現為的行為列表。 yii\base\Component
canGetProperty() 傳回一個值,指出是否可以讀取屬性。 yii\db\BaseActiveRecord
canSetOldAttribute() 傳回是否可以設定舊的具名屬性。 yii\db\BaseActiveRecord
canSetProperty() 傳回一個值,指出是否可以設定屬性。 yii\db\BaseActiveRecord
className() 傳回此類別的完整命名空間名稱。 yii\base\BaseObject
clearErrors() 移除所有屬性或單一屬性的錯誤。 yii\base\Model
createValidators() 根據 rules() 中指定的驗證規則,建立驗證器物件。 yii\base\Model
delete() 刪除對應於此 active record 的資料表列。 yii\db\BaseActiveRecord
deleteAll() 使用提供的條件刪除資料表中的列。 yii\db\BaseActiveRecord
detachBehavior() 從元件中分離行為。 yii\base\Component
detachBehaviors() 從元件中分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
equals() 傳回一個值,表示給定的 active record 是否與目前的 active record 相同。 yii\db\BaseActiveRecord
extraFields() 傳回可以進一步擴展並由 toArray() 傳回的欄位列表。 yii\db\BaseActiveRecord
fields() 傳回當未指定特定欄位時,預設應由 toArray() 傳回的欄位列表。 yii\db\BaseActiveRecord
find() 建立一個 yii\db\ActiveQueryInterface 實例以用於查詢目的。 yii\db\ActiveRecordInterface
findAll() 傳回符合指定主鍵值或一組欄位值的 active record 模型列表。 yii\db\BaseActiveRecord
findOne() 依主鍵或欄位值陣列傳回單一 active record 模型實例。 yii\db\BaseActiveRecord
formName() 傳回此模型類別應使用的表單名稱。 yii\base\Model
generateAttributeLabel() 根據給定的屬性名稱產生使用者友善的屬性標籤。 yii\base\Model
getActiveValidators() 傳回適用於目前 $scenario 的驗證器。 yii\base\Model
getAttribute() 傳回指定名稱的屬性值。 yii\db\BaseActiveRecord
getAttributeHint() 傳回指定屬性的文字提示。 yii\db\BaseActiveRecord
getAttributeLabel() 傳回指定屬性的文字標籤。 yii\db\BaseActiveRecord
getAttributes() 傳回屬性值。 yii\base\Model
getBehavior() 傳回指定名稱的行為物件。 yii\base\Component
getBehaviors() 傳回附加到此元件的所有行為。 yii\base\Component
getDb() 傳回此 AR 類別使用的連線。 yii\db\ActiveRecordInterface
getDirtyAttributes() 傳回自上次載入或儲存後已修改的屬性值。 yii\db\BaseActiveRecord
getErrorSummary() 以一維陣列傳回所有屬性的錯誤摘要。 yii\base\Model
getErrors() 傳回所有屬性或單一屬性的錯誤。 yii\base\Model
getFirstError() 傳回指定屬性的第一個錯誤。 yii\base\Model
getFirstErrors() 傳回模型中每個屬性的第一個錯誤。 yii\base\Model
getIsNewRecord() 傳回一個值,表示目前的記錄是否為新的。 yii\db\BaseActiveRecord
getIterator() 傳回用於遍歷模型中屬性的迭代器。 yii\base\Model
getOldAttribute() 傳回指定名稱屬性的舊值。 yii\db\BaseActiveRecord
getOldAttributes() 傳回舊的屬性值。 yii\db\BaseActiveRecord
getOldPrimaryKey() 傳回舊的主鍵值。 yii\db\BaseActiveRecord
getPrimaryKey() 傳回主鍵值。 yii\db\BaseActiveRecord
getRelatedRecords() 傳回所有已填充的關聯記錄。 yii\db\BaseActiveRecord
getRelation() 傳回具有指定名稱的關聯物件。 yii\db\BaseActiveRecord
getScenario() 傳回此模型中使用的情境。 yii\base\Model
getValidators() 傳回在 rules() 中宣告的所有驗證器。 yii\base\Model
hasAttribute() 傳回一個值,表示模型是否具有指定名稱的屬性。 yii\db\BaseActiveRecord
hasErrors() 傳回一個值,表示是否有任何驗證錯誤。 yii\base\Model
hasEventHandlers() 傳回一個值,表示是否有任何處理常式附加到指定的事件。 yii\base\Component
hasMany() 宣告一個 has-many 關聯。 yii\db\BaseActiveRecord
hasMethod() 傳回一個值,表示是否已定義方法。 yii\base\Component
hasOne() 宣告一個 has-one 關聯。 yii\db\BaseActiveRecord
hasProperty() 傳回一個值,表示是否為此元件定義了屬性。 yii\base\Component
init() 初始化物件。 yii\db\BaseActiveRecord
insert() 使用此記錄的屬性值將記錄插入資料庫。 yii\db\ActiveRecordInterface
instance() 傳回靜態類別實例,可用於取得 meta 資訊。 yii\base\StaticInstanceTrait
instantiate() 建立一個 active record 實例。 yii\db\BaseActiveRecord
isAttributeActive() 傳回一個值,表示屬性在目前情境中是否為 active。 yii\base\Model
isAttributeChanged() 傳回一個值,表示指定名稱的屬性是否已變更。 yii\db\BaseActiveRecord
isAttributeRequired() 傳回一個值,表示屬性是否為必要。 yii\base\Model
isAttributeSafe() 傳回一個值,表示屬性對於大量賦值是否安全。 yii\base\Model
isPrimaryKey() 傳回一個值,表示給定的一組屬性是否代表此模型的主鍵。 yii\db\BaseActiveRecord
isRelationPopulated() 檢查指定名稱的關聯是否已填充記錄。 yii\db\BaseActiveRecord
link() 建立兩個模型之間的關聯。 yii\db\BaseActiveRecord
load() 使用輸入資料填充模型。 yii\base\Model
loadMultiple() 使用來自終端使用者的資料填充一組模型。 yii\base\Model
loadRelations() 為已載入的主模型 eager loads 相關模型。 yii\db\BaseActiveRecord
loadRelationsFor() 為已載入的主模型 eager loads 相關模型。 yii\db\BaseActiveRecord
markAttributeDirty() 將屬性標記為 dirty。 yii\db\BaseActiveRecord
off() 從此元件分離現有的事件處理常式。 yii\base\Component
offsetExists() 傳回在指定偏移量處是否存在元素。 yii\db\BaseActiveRecord
offsetGet() 傳回指定偏移量處的元素。 yii\base\Model
offsetSet() 設定指定偏移量處的元素。 yii\base\Model
offsetUnset() 將指定偏移量處的元素值設定為 null。 yii\db\BaseActiveRecord
on() 將事件處理常式附加到事件。 yii\base\Component
onUnsafeAttribute() 當大量賦值不安全屬性時,會調用此方法。 yii\base\Model
optimisticLock() 傳回儲存鎖定版本以實作 optimistic locking 的欄位名稱。 yii\db\BaseActiveRecord
populateRecord() 使用來自資料庫/儲存體的資料列填充 active record 物件。 yii\db\BaseActiveRecord
populateRelation() 使用相關記錄填充指定名稱的關聯。 yii\db\BaseActiveRecord
primaryKey() 傳回此 AR 類別的主鍵名稱 yii\db\ActiveRecordInterface
refresh() 使用最新的資料重新填充此 active record。 yii\db\BaseActiveRecord
rules() 傳回屬性的驗證規則。 yii\base\Model
safeAttributes() 傳回在目前情境中可以大量賦值的安全屬性名稱。 yii\base\Model
save() 儲存目前的記錄。 yii\db\BaseActiveRecord
scenarios() 傳回情境列表和對應的 active 屬性。 yii\base\Model
setAttribute() 設定指定名稱的屬性值。 yii\db\BaseActiveRecord
setAttributes() 以大量方式設定屬性值。 yii\base\Model
setIsNewRecord() 設定表示記錄是否為新的值。 yii\db\BaseActiveRecord
setOldAttribute() 設定指定名稱屬性的舊值。 yii\db\BaseActiveRecord
setOldAttributes() 設定舊的屬性值。 yii\db\BaseActiveRecord
setScenario() 設定模型的情境。 yii\base\Model
toArray() 將模型轉換為陣列。 yii\base\ArrayableTrait
trigger() 觸發事件。 yii\base\Component
unlink() 摧毀兩個模型之間的關聯。 yii\db\BaseActiveRecord
unlinkAll() 摧毀目前模型中的關聯。 yii\db\BaseActiveRecord
update() 將對此 active record 的變更儲存到相關聯的資料庫表格中。 yii\db\BaseActiveRecord
updateAll() 使用提供的屬性值和條件更新整個表格。 yii\db\BaseActiveRecord
updateAllCounters() 使用提供的計數器變更和條件更新整個表格。 yii\db\BaseActiveRecord
updateAttributes() 更新指定的屬性。 yii\db\BaseActiveRecord
updateCounters() 更新目前 AR 物件的一個或多個計數器欄位。 yii\db\BaseActiveRecord
validate() 執行資料驗證。 yii\base\Model
validateMultiple() 驗證多個模型。 yii\base\Model

Protected Methods

隱藏繼承的方法

方法 描述 定義於
createRelationQuery() has-onehas-many 關聯建立查詢實例。 yii\db\BaseActiveRecord
extractFieldsFor() 從給定根欄位的欄位集合中提取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:"item.id" 前面的範例會提取 "id"。 yii\base\ArrayableTrait
extractRootFields() 從巢狀欄位中提取根欄位名稱。 yii\base\ArrayableTrait
refreshInternal() 使用從新提取的實例取得的最新資料重新填充此 active record。 yii\db\BaseActiveRecord
resolveFields() 判斷哪些欄位可以由 toArray() 傳回。 yii\base\ArrayableTrait
updateInternal() yii\db\BaseActiveRecord

Events

Hide inherited events

Event 類型 描述 定義於
EVENT_AFTER_DELETE yii\db\Event 在記錄刪除後觸發的事件。 yii\db\BaseActiveRecord
EVENT_AFTER_FIND yii\db\Event 在記錄建立並使用查詢結果填充後觸發的事件。 yii\db\BaseActiveRecord
EVENT_AFTER_INSERT yii\db\AfterSaveEvent 在記錄插入後觸發的事件。 yii\db\BaseActiveRecord
EVENT_AFTER_REFRESH yii\db\Event 在記錄重新整理後觸發的事件。(自版本 2.0.8 起可用) yii\db\BaseActiveRecord
EVENT_AFTER_UPDATE yii\db\AfterSaveEvent 在記錄更新後觸發的事件。 yii\db\BaseActiveRecord
EVENT_AFTER_VALIDATE yii\base\Event validate() 結束時引發的事件 yii\base\Model
EVENT_BEFORE_DELETE yii\base\ModelEvent 在刪除記錄之前觸發的事件。 yii\db\BaseActiveRecord
EVENT_BEFORE_INSERT yii\base\ModelEvent 在插入記錄之前觸發的事件。 yii\db\BaseActiveRecord
EVENT_BEFORE_UPDATE yii\base\ModelEvent 在更新記錄之前觸發的事件。 yii\db\BaseActiveRecord
EVENT_BEFORE_VALIDATE yii\base\ModelEvent validate() 開始時引發的事件。 yii\base\Model
EVENT_INIT yii\db\Event 在透過 init() 初始化記錄時觸發的事件。 yii\db\BaseActiveRecord

Constants

Hide inherited constants

Constant Value 描述 定義於
SCENARIO_DEFAULT 'default' 預設情境的名稱。 yii\base\Model

Property Details

隱藏繼承的屬性

$dirtyAttributes public property

已變更的屬性值(名稱-值對)。

public array $dirtyAttributes null
$isNewRecord public property

記錄是否為新的,且在呼叫 save() 時應插入。

public boolean $isNewRecord null
$oldAttributes public property

舊的屬性值(名稱-值 配對)。請注意,此屬性的類型在 getter 和 setter 中有所不同。請參閱 getOldAttributes()setOldAttributes() 以取得詳細資訊。

public array $oldAttributes null
$oldPrimaryKey public property

舊的主鍵值。如果主鍵是複合主鍵或 $asArraytrue,則傳回陣列(欄位名稱 => 欄位值)。否則傳回字串(如果鍵值為 null,則傳回 null)。

public mixed $oldPrimaryKey null
$primaryKey public property

主鍵值。如果主鍵是複合主鍵或 $asArraytrue,則傳回陣列(欄位名稱 => 欄位值)。否則傳回字串(如果鍵值為 null,則傳回 null)。

public mixed $primaryKey null
$relatedRecords public property

依關聯名稱索引的關聯記錄陣列。

public array $relatedRecords null

Method Details

隱藏繼承的方法

__call() public method

Defined in: yii\base\Component::__call()

呼叫非類別方法的具名方法。

此方法將檢查是否有任何附加的行為具有指定名稱的方法,並在可用的情況下執行它。

請勿直接呼叫此方法,因為它是 PHP magic method,當調用未知的 method 時,它會被隱式呼叫。

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()");
}

            
__clone() public method

Defined in: yii\base\Model::__clone()

在透過複製現有物件建立物件後,會呼叫此方法。

它會移除所有行為,因為它們附加到舊的物件。

public void __clone ( )

                public function __clone()
{
    parent::__clone();
    $this->_errors = null;
    $this->_validators = null;
}

            
__construct() public method

Defined in: yii\base\BaseObject::__construct()

建構子。

預設實作會執行兩件事

  • 使用給定的組態 $config 初始化物件。
  • 呼叫 init()

如果子類別中覆寫了此方法,建議

  • 建構子的最後一個參數是組態陣列,例如此處的 $config
  • 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] )
$config array

將用於初始化物件屬性的名稱-值 配對

                public function __construct($config = [])
{
    if (!empty($config)) {
        Yii::configure($this, $config);
    }
    $this->init();
}

            
__get() public method

PHP getter 魔術方法。

覆寫此方法,以便可以像屬性一樣存取屬性和相關物件。

另請參閱 getAttribute()

public mixed __get ( $name )
$name string

屬性名稱

return mixed

屬性值

throws yii\base\InvalidArgumentException

如果關聯名稱錯誤

                public function __get($name)
{
    if (array_key_exists($name, $this->_attributes)) {
        return $this->_attributes[$name];
    }
    if ($this->hasAttribute($name)) {
        return null;
    }
    if (array_key_exists($name, $this->_related)) {
        return $this->_related[$name];
    }
    $value = parent::__get($name);
    if ($value instanceof ActiveQueryInterface) {
        $this->setRelationDependencies($name, $value);
        return $this->_related[$name] = $value->findFor($name, $this);
    }
    return $value;
}

            
__isset() public method

檢查屬性值是否為 null。

此方法覆寫父類別實作,方法是檢查指定名稱的屬性是否為 null

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

屬性值是否為 null

                public function __isset($name)
{
    try {
        return $this->__get($name) !== null;
    } catch (\Exception $t) {
        return false;
    } catch (\Throwable $e) {
        return false;
    }
}

            
__set() public method

PHP setter 魔術方法。

覆寫此方法,以便可以像屬性一樣存取 AR 屬性。

public void __set ( $name, $value )
$name string

屬性名稱

$value mixed

屬性值

                public function __set($name, $value)
{
    if ($this->hasAttribute($name)) {
        if (
            !empty($this->_relationsDependencies[$name])
            && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
        ) {
            $this->resetDependentRelations($name);
        }
        $this->_attributes[$name] = $value;
    } else {
        parent::__set($name, $value);
    }
}

            
__unset() public method

將元件屬性設定為 null。

此方法覆寫父類別實作,方法是清除指定的屬性值。

public void __unset ( $name )
$name string

屬性名稱或事件名稱

                public function __unset($name)
{
    if ($this->hasAttribute($name)) {
        unset($this->_attributes[$name]);
        if (!empty($this->_relationsDependencies[$name])) {
            $this->resetDependentRelations($name);
        }
    } elseif (array_key_exists($name, $this->_related)) {
        unset($this->_related[$name]);
    } elseif ($this->getRelation($name, false) === null) {
        parent::__unset($name);
    }
}

            
activeAttributes() public method

Defined in: yii\base\Model::activeAttributes()

傳回目前情境中需要驗證的屬性名稱。

public string[] activeAttributes ( )
return string[]

安全屬性名稱

                public function activeAttributes()
{
    $scenario = $this->getScenario();
    $scenarios = $this->scenarios();
    if (!isset($scenarios[$scenario])) {
        return [];
    }
    $attributes = array_keys(array_flip($scenarios[$scenario]));
    foreach ($attributes as $i => $attribute) {
        if (strncmp($attribute, '!', 1) === 0) {
            $attributes[$i] = substr($attribute, 1);
        }
    }
    return $attributes;
}

            
addError() public method

Defined in: yii\base\Model::addError()

將新錯誤新增至指定的屬性。

public void addError ( $attribute, $error '' )
$attribute string

屬性名稱

$error string

新的錯誤訊息

                public function addError($attribute, $error = '')
{
    $this->_errors[$attribute][] = $error;
}

            
addErrors() public method (available since version 2.0.2)

Defined in: yii\base\Model::addErrors()

新增錯誤列表。

public void addErrors ( array $items )
$items array

錯誤列表。陣列鍵必須是屬性名稱。陣列值應為錯誤訊息。如果屬性有多個錯誤,則必須以陣列的形式給出這些錯誤。您可以將 getErrors() 的結果用作此參數的值。

                public function addErrors(array $items)
{
    foreach ($items as $attribute => $errors) {
        if (is_array($errors)) {
            foreach ($errors as $error) {
                $this->addError($attribute, $error);
            }
        } else {
            $this->addError($attribute, $errors);
        }
    }
}

            
afterDelete() public method

刪除記錄後會調用此方法。

預設實作會引發 EVENT_AFTER_DELETE 事件。您可以覆寫此方法,在記錄刪除後執行後續處理。請確保您呼叫父類別實作,以便正確引發事件。

public void afterDelete ( )

                public function afterDelete()
{
    $this->trigger(self::EVENT_AFTER_DELETE);
}

            
afterFind() public method

當建立 AR 物件並使用查詢結果填入時,會呼叫此方法。

預設實作將觸發 EVENT_AFTER_FIND 事件。當覆寫此方法時,請確保您呼叫父類別實作,以確保事件被觸發。

public void afterFind ( )

                public function afterFind()
{
    $this->trigger(self::EVENT_AFTER_FIND);
}

            
afterRefresh() public method (available since version 2.0.8)

重新整理 AR 物件時會呼叫此方法。

預設實作將觸發 EVENT_AFTER_REFRESH 事件。當覆寫此方法時,請確保您呼叫父類別實作,以確保事件被觸發。

public void afterRefresh ( )

                public function afterRefresh()
{
    $this->trigger(self::EVENT_AFTER_REFRESH);
}

            
afterSave() public method

在插入或更新記錄結束時會呼叫此方法。

$inserttrue 時,預設實作將觸發 EVENT_AFTER_INSERT 事件;如果 $insertfalse,則觸發 EVENT_AFTER_UPDATE 事件。使用的事件類別是 yii\db\AfterSaveEvent。當覆寫此方法時,請確保您呼叫父類別實作,以便觸發事件。

public void afterSave ( $insert, $changedAttributes )
$insert boolean

當插入記錄時是否呼叫此方法。如果為 false,則表示在更新記錄時呼叫此方法。

$changedAttributes array

已變更並儲存的屬性的舊值。您可以使用此參數根據所做的變更採取動作,例如在密碼已變更時發送電子郵件,或實作追蹤所有變更的稽核追蹤。 $changedAttributes 為您提供舊的屬性值,而 active record ($this) 已具有新的、更新的值。

請注意,預設情況下不執行自動類型轉換。您可以使用 yii\behaviors\AttributeTypecastBehavior 來協助屬性類型轉換。請參閱 https://yii.dev.org.tw/doc-2.0/guide-db-active-record.html#attributes-typecasting

                public function afterSave($insert, $changedAttributes)
{
    $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
        'changedAttributes' => $changedAttributes,
    ]));
}

            
afterValidate() public method

Defined in: yii\base\Model::afterValidate()

驗證結束後會調用此方法。

預設實作會引發 afterValidate 事件。您可以覆寫此方法,在驗證後執行後續處理。請確保調用父類別實作,以便可以引發事件。

public void afterValidate ( )

                public function afterValidate()
{
    $this->trigger(self::EVENT_AFTER_VALIDATE);
}

            
attachBehavior() public method

Defined in: 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);
}

            
attachBehaviors() public method

定義於: 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);
    }
}

            
attributeHints() public method (自版本 2.0.4 起可用)

定義於: yii\base\Model::attributeHints()

傳回屬性提示。

屬性提示主要用於顯示目的。例如,給定一個屬性 isPublic,我們可以宣告一個提示 Whether the post should be visible for not logged in users(貼文是否應對未登入的使用者可見),這提供了屬性含義的使用者友善描述,並且可以顯示給終端使用者。

與標籤不同,如果省略其顯式宣告,則不會產生提示。

請注意,為了繼承父類別中定義的提示,子類別需要使用諸如 array_merge() 之類的函式將父提示與子提示合併。

public array attributeHints ( )
return array

屬性提示(名稱 => 提示)

                public function attributeHints()
{
    return [];
}

            
attributeLabels() public method

定義於: yii\base\Model::attributeLabels()

傳回屬性標籤。

屬性標籤主要用於顯示目的。例如,給定一個屬性 firstName,我們可以宣告一個標籤 First Name(名字),它更使用者友善,並且可以顯示給終端使用者。

預設情況下,屬性標籤是使用 generateAttributeLabel() 產生的。此方法允許您顯式指定屬性標籤。

請注意,為了繼承父類別中定義的標籤,子類別需要使用諸如 array_merge() 之類的函式將父標籤與子標籤合併。

另請參閱 generateAttributeLabel()

public array attributeLabels ( )
return array

屬性標籤(名稱 => 標籤)

                public function attributeLabels()
{
    return [];
}

            
attributes() public method

定義於: yii\base\Model::attributes()

傳回屬性名稱列表。

預設情況下,此方法會傳回類別的所有 public 非靜態屬性。您可以覆寫此方法以變更預設行為。

public string[] attributes ( )
return string[]

屬性名稱列表。

                public function attributes()
{
    $class = new ReflectionClass($this);
    $names = [];
    foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) {
        if (!$property->isStatic()) {
            $names[] = $property->getName();
        }
    }
    return $names;
}

            
beforeDelete() public method

刪除記錄之前會調用此方法。

預設實作會引發 EVENT_BEFORE_DELETE 事件。在覆寫此方法時,請確保您像以下這樣呼叫父實作

public function beforeDelete()
{
    if (!parent::beforeDelete()) {
        return false;
    }

    // ...custom code here...
    return true;
}
public boolean beforeDelete ( )
return boolean

是否應刪除記錄。預設值為 true

                public function beforeDelete()
{
    $event = new ModelEvent();
    $this->trigger(self::EVENT_BEFORE_DELETE, $event);
    return $event->isValid;
}

            
beforeSave() public method

在插入或更新記錄開始時會呼叫此方法。

$inserttrue 時,預設實作將觸發 EVENT_BEFORE_INSERT 事件,如果 $insertfalse,則觸發 EVENT_BEFORE_UPDATE 事件。在覆寫此方法時,請確保您像以下這樣呼叫父實作

public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    // ...custom code here...
    return true;
}
public boolean beforeSave ( $insert )
$insert boolean

當插入記錄時是否呼叫此方法。如果為 false,則表示在更新記錄時呼叫此方法。

return boolean

是否應繼續插入或更新。如果為 false,則將取消插入或更新。

                public function beforeSave($insert)
{
    $event = new ModelEvent();
    $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
    return $event->isValid;
}

            
beforeValidate() public method

定義於: yii\base\Model::beforeValidate()

驗證開始之前會調用此方法。

預設實作會引發 beforeValidate 事件。您可以覆寫此方法以在驗證之前執行初步檢查。請確保調用父實作,以便可以引發事件。

public boolean beforeValidate ( )
return boolean

是否應執行驗證。預設值為 true。如果傳回 false,則驗證將停止,並且模型被視為無效。

                public function beforeValidate()
{
    $event = new ModelEvent();
    $this->trigger(self::EVENT_BEFORE_VALIDATE, $event);
    return $event->isValid;
}

            
behaviors() public method

定義於: 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 [];
}

            
canGetProperty() public method

傳回一個值,指出是否可以讀取屬性。

如果滿足以下條件,則可以讀取屬性

  • 類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。
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 (parent::canGetProperty($name, $checkVars, $checkBehaviors)) {
        return true;
    }
    try {
        return $this->hasAttribute($name);
    } catch (\Exception $e) {
        // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
        return false;
    }
}

            
canSetOldAttribute() public method

傳回是否可以設定舊的具名屬性。

另請參閱 setOldAttribute()

public boolean canSetOldAttribute ( $name )
$name string

屬性名稱

return boolean

是否可以設定舊屬性

                public function canSetOldAttribute($name)
{
    return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
}

            
canSetProperty() public method

傳回一個值,指出是否可以設定屬性。

如果滿足以下條件,則可以寫入屬性

  • 類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫屬性(當 $checkBehaviors 為 true 時)。
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 (parent::canSetProperty($name, $checkVars, $checkBehaviors)) {
        return true;
    }
    try {
        return $this->hasAttribute($name);
    } catch (\Exception $e) {
        // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
        return false;
    }
}

            
className() public static method
自 2.0.14 版本起已過時。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整命名空間名稱。

public static string className ( )
return string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
clearErrors() public method

定義於: yii\base\Model::clearErrors()

移除所有屬性或單一屬性的錯誤。

public void clearErrors ( $attribute null )
$attribute string|null

屬性名稱。使用 null 以移除所有屬性的錯誤。

                public function clearErrors($attribute = null)
{
    if ($attribute === null) {
        $this->_errors = [];
    } else {
        unset($this->_errors[$attribute]);
    }
}

            
createRelationQuery() protected method (自版本 2.0.12 起可用)

has-onehas-many 關聯建立查詢實例。

另請參閱

protected yii\db\ActiveQueryInterface createRelationQuery ( $class, $link, $multiple )
$class string

相關記錄的類別名稱。

$link array

主鍵-外鍵約束。

$multiple boolean

此查詢是否表示與多個記錄的關聯。

return yii\db\ActiveQueryInterface

關聯式查詢物件。

                protected function createRelationQuery($class, $link, $multiple)
{
    /* @var $class ActiveRecordInterface */
    /* @var $query ActiveQuery */
    $query = $class::find();
    $query->primaryModel = $this;
    $query->link = $link;
    $query->multiple = $multiple;
    return $query;
}

            
createValidators() public method

定義於: yii\base\Model::createValidators()

根據 rules() 中指定的驗證規則,建立驗證器物件。

getValidators() 不同,每次呼叫此方法時,都會傳回新的驗證器列表。

public ArrayObject createValidators ( )
return ArrayObject

驗證器

throws yii\base\InvalidConfigException

如果任何驗證規則組態無效

                public function createValidators()
{
    $validators = new ArrayObject();
    foreach ($this->rules() as $rule) {
        if ($rule instanceof Validator) {
            $validators->append($rule);
        } elseif (is_array($rule) && isset($rule[0], $rule[1])) { // attributes, validator type
            $validator = Validator::createValidator($rule[1], $this, (array) $rule[0], array_slice($rule, 2));
            $validators->append($validator);
        } else {
            throw new InvalidConfigException('Invalid validation rule: a rule must specify both attribute names and validator type.');
        }
    }
    return $validators;
}

            
delete() public method

刪除對應於此 active record 的資料表列。

此方法按順序執行以下步驟

  1. 呼叫 beforeDelete()。如果該方法傳回 false,它將跳過其餘步驟;
  2. 從資料庫中刪除記錄;
  3. 呼叫 afterDelete()

在上述步驟 1 和 3 中,名為 EVENT_BEFORE_DELETEEVENT_AFTER_DELETE 的事件將由相應的方法引發。

public integer|false delete ( )
return integer|false

刪除的列數,如果由於某些原因刪除不成功,則為 false。請注意,即使刪除執行成功,刪除的列數也可能為 0。

throws yii\db\StaleObjectException

如果啟用樂觀鎖定,並且要刪除的資料已過時。

throws yii\db\Exception

如果刪除失敗。

                public function delete()
{
    $result = false;
    if ($this->beforeDelete()) {
        // we do not check the return value of deleteAll() because it's possible
        // the record is already deleted in the database and thus the method will return 0
        $condition = $this->getOldPrimaryKey(true);
        $lock = $this->optimisticLock();
        if ($lock !== null) {
            $condition[$lock] = $this->$lock;
        }
        $result = static::deleteAll($condition);
        if ($lock !== null && !$result) {
            throw new StaleObjectException('The object being deleted is outdated.');
        }
        $this->_oldAttributes = null;
        $this->afterDelete();
    }
    return $result;
}

            
deleteAll() public static method

使用提供的條件刪除資料表中的列。

警告:如果您未指定任何條件,此方法將刪除表格中的所有列。

例如,要刪除所有狀態為 3 的客戶

Customer::deleteAll('status = 3');
public static integer deleteAll ( $condition null )
$condition string|array|null

將放在 DELETE SQL 的 WHERE 部分中的條件。請參閱 yii\db\Query::where(),以瞭解如何指定此參數。

return integer

刪除的列數

throws yii\base\NotSupportedException

如果未覆寫。

                public static function deleteAll($condition = null)
{
    throw new NotSupportedException(__METHOD__ . ' is not supported.');
}

            
detachBehavior() public method

定義於: 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;
}

            
detachBehaviors() public method

定義於: yii\base\Component::detachBehaviors()

從元件中分離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
ensureBehaviors() public method

定義於: 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);
        }
    }
}

            
equals() public method

傳回一個值,表示給定的 active record 是否與目前的 active record 相同。

透過比較兩個活動記錄的表格名稱和主鍵值來進行比較。如果其中一個記錄是新記錄,它們也被認為不相等。

public boolean equals ( $record )
$record yii\db\ActiveRecordInterface

要比較的記錄

return boolean

兩個活動記錄是否指向同一個資料庫表格中的同一列。

                public function equals($record)
{
    if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
        return false;
    }
    return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
}

            
extraFields() public method

傳回可以進一步擴展並由 toArray() 傳回的欄位列表。

預設實作會傳回已填入此記錄的關係名稱。

此方法類似於 fields(),不同之處在於此方法傳回的欄位列表預設情況下不會由 toArray() 傳回。只有在呼叫 toArray() 時明確指定要展開的欄位名稱時,才會匯出其值。

預設實作會傳回一個空陣列。

您可以覆寫此方法,以根據某些上下文資訊(例如,當前應用程式使用者)傳回可展開欄位的列表。

public array extraFields ( )
return array

可展開的欄位名稱或欄位定義的列表。請參閱 fields(),以瞭解傳回值的格式。

                public function extraFields()
{
    $fields = array_keys($this->getRelatedRecords());
    return array_combine($fields, $fields);
}

            
extractFieldsFor() protected method (自版本 2.0.14 起可用)

定義於: yii\base\ArrayableTrait::extractFieldsFor()

從給定根欄位的欄位集合中提取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:"item.id" 前面的範例會提取 "id"。

protected array extractFieldsFor ( array $fields, $rootField )
$fields array

請求提取的欄位

$rootField string

我們要為其提取巢狀欄位的根欄位

return array

為給定欄位提取的巢狀欄位

                protected function extractFieldsFor(array $fields, $rootField)
{
    $result = [];
    foreach ($fields as $field) {
        if (0 === strpos($field, "{$rootField}.")) {
            $result[] = preg_replace('/^' . preg_quote($rootField, '/') . '\./i', '', $field);
        }
    }
    return array_unique($result);
}

            
extractRootFields() protected method (自版本 2.0.14 起可用)

定義於: yii\base\ArrayableTrait::extractRootFields()

從巢狀欄位中提取根欄位名稱。

巢狀欄位以點 (.) 分隔。例如:"item.id" 前面的範例將提取 "item"。

protected array extractRootFields ( array $fields )
$fields array

請求提取的欄位

return array

從給定的巢狀欄位中提取的根欄位

                protected function extractRootFields(array $fields)
{
    $result = [];
    foreach ($fields as $field) {
        $result[] = current(explode('.', $field, 2));
    }
    if (in_array('*', $result, true)) {
        $result = [];
    }
    return array_unique($result);
}

            
fields() public method

傳回當未指定特定欄位時,預設應由 toArray() 傳回的欄位列表。

預設實作會傳回已填入此記錄的欄位名稱。

欄位是 toArray() 傳回的陣列中的具名元素。

此方法應傳回欄位名稱或欄位定義的陣列。如果是前者,欄位名稱將被視為物件屬性名稱,其值將用作欄位值。如果是後者,陣列鍵應為欄位名稱,而陣列值應為相應的欄位定義,它可以是物件屬性名稱或傳回相應欄位值的 PHP 可呼叫函式。可呼叫函式的簽名應為

function ($model, $field) {
    // return field value
}

例如,以下程式碼宣告了四個欄位

  • email:欄位名稱與屬性名稱 email 相同;
  • firstNamelastName:欄位名稱為 firstNamelastName,其值從 first_namelast_name 屬性取得;
  • fullName:欄位名稱為 fullName。其值是透過串連 first_namelast_name 取得的。
return [
    'email',
    'firstName' => 'first_name',
    'lastName' => 'last_name',
    'fullName' => function ($model) {
        return $model->first_name . ' ' . $model->last_name;
    },
];

在此方法中,您可能還希望根據某些上下文資訊傳回不同的欄位列表。例如,根據 $scenario 或當前應用程式使用者的權限,您可以傳回不同的可見欄位集或篩選掉某些欄位。

此方法的預設實作會傳回以相同屬性名稱索引的 attributes()

public array fields ( )
return array

欄位名稱或欄位定義的列表。

                public function fields()
{
    $fields = array_keys($this->_attributes);
    return array_combine($fields, $fields);
}

            
find() public abstract static method

Defined in: yii\db\ActiveRecordInterface::find()

建立一個 yii\db\ActiveQueryInterface 實例以用於查詢目的。

傳回的 yii\db\ActiveQueryInterface 實例可以透過呼叫 yii\db\ActiveQueryInterface 中定義的方法進一步自訂,然後再呼叫 one()all() 以傳回已填充的 ActiveRecord 實例。 例如:

// find the customer whose ID is 1
$customer = Customer::find()->where(['id' => 1])->one();

// find all active customers and order them by their age:
$customers = Customer::find()
    ->where(['status' => 1])
    ->orderBy('age')
    ->all();

此方法也會被 yii\db\BaseActiveRecord::hasOne()yii\db\BaseActiveRecord::hasMany() 呼叫,以建立關聯式查詢。

您可以覆寫此方法以傳回自訂的查詢。 例如:

class Customer extends ActiveRecord
{
    public static function find()
    {
        // use CustomerQuery instead of the default ActiveQuery
        return new CustomerQuery(get_called_class());
    }
}

以下程式碼示範如何為所有查詢套用預設條件

class Customer extends ActiveRecord
{
    public static function find()
    {
        return parent::find()->where(['deleted' => false]);
    }
}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM customer WHERE `deleted`=:deleted AND age>30
$customers = Customer::find()->andWhere('age>30')->all();

// Use where() to ignore the default condition
// SELECT FROM customer WHERE age>30
$customers = Customer::find()->where('age>30')->all();
public abstract static yii\db\ActiveQueryInterface find ( )
return yii\db\ActiveQueryInterface

新建立的 yii\db\ActiveQueryInterface 實例。

                public static function find();

            
findAll() public static method

傳回符合指定主鍵值或一組欄位值的 active record 模型列表。

此方法接受

  • 純量值(整數或字串):依單一主鍵值查詢,並傳回包含對應記錄的陣列(若未找到則傳回空陣列)。
  • 非關聯式陣列:依主鍵值列表查詢,並傳回對應的記錄(若未找到任何記錄則傳回空陣列)。 請注意,空條件將產生空的結果,因為它會被解釋為搜尋主鍵,而不是空的 WHERE 條件。
  • 名稱-值配對的關聯式陣列:依一組屬性值查詢,並傳回符合所有屬性值的記錄陣列(若未找到任何記錄則傳回空陣列)。 請注意,['id' => 1, 2] 會被視為非關聯式陣列。 對於 SQL DBMS,欄位名稱僅限於目前記錄表格的欄位,否則會進行篩選,僅限於簡單的篩選條件。
  • yii\db\Expression:運算式將會直接使用。 (@since 2.0.37)

此方法將自動呼叫 all() 方法,並傳回 ActiveRecord 實例的陣列。

注意:由於這僅是簡寫方法,因此使用更複雜的條件(例如 ['!=', 'id', 1])將無法運作。 如果您需要指定更複雜的條件,請改為搭配 where() 使用 find()

請參閱以下程式碼以取得使用範例

// find the customers whose primary key value is 10
$customers = Customer::findAll(10);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();

如果您需要將使用者輸入傳遞至此方法,請確保輸入值為純量,或者在陣列條件的情況下,請確保陣列結構無法從外部變更

// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static[] findAll ( $condition )
$condition mixed

主鍵值或一組欄位值

return static[]

ActiveRecord 實例的陣列,或若沒有符合的項目則傳回空陣列。

                public static function findAll($condition)
{
    return static::findByCondition($condition)->all();
}

            
findOne() public static method

依主鍵或欄位值陣列傳回單一 active record 模型實例。

此方法接受

  • 純量值(整數或字串):依單一主鍵值查詢,並傳回對應的記錄(若未找到則傳回 null)。
  • 非關聯式陣列:依主鍵值列表查詢,並傳回第一個記錄(若未找到則傳回 null)。
  • 名稱-值配對的關聯式陣列:依一組屬性值查詢,並傳回符合所有屬性值的單一記錄(若未找到則傳回 null)。 請注意,['id' => 1, 2] 會被視為非關聯式陣列。 對於 SQL DBMS,欄位名稱僅限於目前記錄表格的欄位,否則會進行篩選,僅限於簡單的篩選條件。
  • yii\db\Expression:運算式將會直接使用。 (@since 2.0.37)

此方法將自動呼叫 one() 方法,並傳回 ActiveRecord 實例。

注意:由於這僅是簡寫方法,因此使用更複雜的條件(例如 ['!=', 'id', 1])將無法運作。 如果您需要指定更複雜的條件,請改為搭配 where() 使用 find()

請參閱以下程式碼以取得使用範例

// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);

// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();

// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();

如果您需要將使用者輸入傳遞至此方法,請確保輸入值為純量,或者在陣列條件的情況下,請確保陣列結構無法從外部變更

// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
public static static|null findOne ( $condition )
$condition mixed

主鍵值或一組欄位值

return static|null

符合條件的 ActiveRecord 實例,若沒有符合的項目則傳回 null

                public static function findOne($condition)
{
    return static::findByCondition($condition)->one();
}

            
formName() public method

Defined in: yii\base\Model::formName()

傳回此模型類別應使用的表單名稱。

表單名稱主要由 yii\widgets\ActiveForm 使用,以決定如何命名模型中屬性的輸入欄位。 如果表單名稱為 "A",而屬性名稱為 "b",則對應的輸入名稱將為 "A[b]"。 如果表單名稱為空字串,則輸入名稱將為 "b"。

上述命名架構的目的是,對於包含多個不同模型的表單,每個模型的屬性都會在 POST 資料的子陣列中分組,這樣更容易區分它們。

預設情況下,此方法會傳回模型類別名稱(不含命名空間部分)作為表單名稱。 當模型用於不同的表單時,您可以覆寫它。

另請參閱 load()

public string formName ( )
return string

此模型類別的表單名稱。

throws yii\base\InvalidConfigException

當表單使用匿名類別定義且未覆寫 formName() 方法時。

                public function formName()
{
    $reflector = new ReflectionClass($this);
    if (PHP_VERSION_ID >= 70000 && $reflector->isAnonymous()) {
        throw new InvalidConfigException('The "formName()" method should be explicitly defined for anonymous models');
    }
    return $reflector->getShortName();
}

            
generateAttributeLabel() public method

Defined in: yii\base\Model::generateAttributeLabel()

根據給定的屬性名稱產生使用者友善的屬性標籤。

這是透過將底線、破折號和點替換為空格,並將每個單字的首字母改為大寫來完成的。 例如,'department_name' 或 'DepartmentName' 將產生 'Department Name'。

public string generateAttributeLabel ( $name )
$name string

欄位名稱

return string

屬性標籤

                public function generateAttributeLabel($name)
{
    return Inflector::camel2words($name, true);
}

            
getActiveValidators() public method

Defined in: yii\base\Model::getActiveValidators()

傳回適用於目前 $scenario 的驗證器。

public yii\validators\Validator[] getActiveValidators ( $attribute null )
$attribute string|null

應傳回其適用驗證器的屬性名稱。 如果為 null,則將傳回模型中所有屬性的驗證器。

return yii\validators\Validator[]

適用於目前 $scenario 的驗證器。

                public function getActiveValidators($attribute = null)
{
    $activeAttributes = $this->activeAttributes();
    if ($attribute !== null && !in_array($attribute, $activeAttributes, true)) {
        return [];
    }
    $scenario = $this->getScenario();
    $validators = [];
    foreach ($this->getValidators() as $validator) {
        if ($attribute === null) {
            $validatorAttributes = $validator->getValidationAttributes($activeAttributes);
            $attributeValid = !empty($validatorAttributes);
        } else {
            $attributeValid = in_array($attribute, $validator->getValidationAttributes($attribute), true);
        }
        if ($attributeValid && $validator->isActive($scenario)) {
            $validators[] = $validator;
        }
    }
    return $validators;
}

            
getAttribute() public method

傳回指定名稱的屬性值。

如果此記錄是查詢的結果,且屬性未載入,則會傳回 null

另請參閱 hasAttribute()

public mixed getAttribute ( $name )
$name string

屬性名稱

return mixed

屬性值。 如果屬性未設定或不存在,則為 null

                public function getAttribute($name)
{
    return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
}

            
getAttributeHint() public method (available since version 2.0.4)

傳回指定屬性的文字提示。

如果屬性看起來像 relatedModel.attribute,則將從相關模型接收屬性。

另請參閱 attributeHints()

public string getAttributeHint ( $attribute )
$attribute string

屬性名稱

return string

屬性提示

                public function getAttributeHint($attribute)
{
    $hints = $this->attributeHints();
    if (isset($hints[$attribute])) {
        return $hints[$attribute];
    } elseif (strpos($attribute, '.')) {
        $attributeParts = explode('.', $attribute);
        $neededAttribute = array_pop($attributeParts);
        $relatedModel = $this;
        foreach ($attributeParts as $relationName) {
            if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
                $relatedModel = $relatedModel->$relationName;
            } else {
                try {
                    $relation = $relatedModel->getRelation($relationName);
                } catch (InvalidParamException $e) {
                    return '';
                }
                /* @var $modelClass ActiveRecordInterface */
                $modelClass = $relation->modelClass;
                $relatedModel = $modelClass::instance();
            }
        }
        $hints = $relatedModel->attributeHints();
        if (isset($hints[$neededAttribute])) {
            return $hints[$neededAttribute];
        }
    }
    return '';
}

            
getAttributeLabel() public method

傳回指定屬性的文字標籤。

屬性可以點格式指定,以從相關模型檢索標籤,或允許此模型覆寫相關模型中定義的標籤。 例如,如果屬性指定為 'relatedModel1.relatedModel2.attr',則函式將依以下順序傳回它可以找到的第一個標籤定義

  • 在此模型的 attributeLabels() 中定義的 'relatedModel1.relatedModel2.attr' 的標籤;
  • 由此模型的關聯 'relatedModel1' 表示的相關模型中定義的 'relatedModel2.attr' 的標籤;
  • 由關聯 'relatedModel1' 的關聯 'relatedModel2' 表示的相關模型中定義的 'attr' 的標籤。 如果找不到標籤定義,則將傳回 $this->generateAttributeLabel('relatedModel1.relatedModel2.attr') 的值。

另請參閱

public string getAttributeLabel ( $attribute )
$attribute string

屬性名稱

return string

屬性標籤

                public function getAttributeLabel($attribute)
{
    $model = $this;
    $modelAttribute = $attribute;
    for (;;) {
        $labels = $model->attributeLabels();
        if (isset($labels[$modelAttribute])) {
            return $labels[$modelAttribute];
        }
        $parts = explode('.', $modelAttribute, 2);
        if (count($parts) < 2) {
            break;
        }
        list ($relationName, $modelAttribute) = $parts;
        if ($model->isRelationPopulated($relationName) && $model->$relationName instanceof self) {
            $model = $model->$relationName;
        } else {
            try {
                $relation = $model->getRelation($relationName);
            } catch (InvalidArgumentException $e) {
                break;
            }
            /* @var $modelClass ActiveRecordInterface */
            $modelClass = $relation->modelClass;
            $model = $modelClass::instance();
        }
    }
    return $this->generateAttributeLabel($attribute);
}

            
getAttributes() public method

Defined in: yii\base\Model::getAttributes()

傳回屬性值。

public array getAttributes ( $names null, $except = [] )
$names array|null

需要傳回其值的屬性列表。 預設為 null,表示將傳回 attributes() 中列出的所有屬性。 如果是陣列,則只會傳回陣列中的屬性。

$except array

不應傳回其值的屬性列表。

return array

屬性值 (name => value)。

                public function getAttributes($names = null, $except = [])
{
    $values = [];
    if ($names === null) {
        $names = $this->attributes();
    }
    foreach ($names as $name) {
        $values[$name] = $this->$name;
    }
    foreach ($except as $name) {
        unset($values[$name]);
    }
    return $values;
}

            
getBehavior() public method

Defined in: 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;
}

            
getBehaviors() public method

Defined in: yii\base\Component::getBehaviors()

傳回附加到此元件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
return yii\base\Behavior[]

附加到此元件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getDb() public abstract static method

Defined in: yii\db\ActiveRecordInterface::getDb()

傳回此 AR 類別使用的連線。

public abstract static mixed getDb ( )
return mixed

此 AR 類別使用的資料庫連線。

                public static function getDb();

            
getDirtyAttributes() public method

傳回自上次載入或儲存後已修改的屬性值。

新值和舊值的比較是針對使用 === 的相同值進行的。

public array getDirtyAttributes ( $names null )
$names string[]|null

如果最近變更,可能會傳回其值的屬性名稱。 如果為 null,將使用 attributes()

return array

已變更的屬性值(名稱-值配對)

                public function getDirtyAttributes($names = null)
{
    if ($names === null) {
        $names = $this->attributes();
    }
    $names = array_flip($names);
    $attributes = [];
    if ($this->_oldAttributes === null) {
        foreach ($this->_attributes as $name => $value) {
            if (isset($names[$name])) {
                $attributes[$name] = $value;
            }
        }
    } else {
        foreach ($this->_attributes as $name => $value) {
            if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
                $attributes[$name] = $value;
            }
        }
    }
    return $attributes;
}

            
getErrorSummary() public method (available since version 2.0.14)

Defined in: yii\base\Model::getErrorSummary()

以一維陣列傳回所有屬性的錯誤摘要。

另請參閱

public array getErrorSummary ( $showAllErrors )
$showAllErrors boolean

布林值,如果設定為 true,則會顯示每個屬性的每個錯誤訊息,否則只會顯示每個屬性的第一個錯誤訊息。

return array

所有屬性的錯誤,以一維陣列形式呈現。 如果沒有錯誤,則傳回空陣列。

                public function getErrorSummary($showAllErrors)
{
    $lines = [];
    $errors = $showAllErrors ? $this->getErrors() : $this->getFirstErrors();
    foreach ($errors as $es) {
        $lines = array_merge($lines, (array)$es);
    }
    return $lines;
}

            
getErrors() public method

Defined in: yii\base\Model::getErrors()

傳回所有屬性或單一屬性的錯誤。

另請參閱

public array getErrors ( $attribute null )
$attribute string|null

屬性名稱。 使用 null 檢索所有屬性的錯誤。

return array

所有屬性或指定屬性的錯誤。 如果沒有錯誤,則傳回空陣列。 請參閱 getErrors() 以取得詳細說明。 請注意,當傳回所有屬性的錯誤時,結果會是二維陣列,如下所示

[
    'username' => [
        'Username is required.',
        'Username must contain only word characters.',
    ],
    'email' => [
        'Email address is invalid.',
    ]
]

                public function getErrors($attribute = null)
{
    if ($attribute === null) {
        return $this->_errors === null ? [] : $this->_errors;
    }
    return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
}

            
getFirstError() public method

Defined in: yii\base\Model::getFirstError()

傳回指定屬性的第一個錯誤。

另請參閱

public string|null getFirstError ( $attribute )
$attribute string

屬性名稱。

return string|null

錯誤訊息。 如果沒有錯誤,則傳回 Null。

                public function getFirstError($attribute)
{
    return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
}

            
getFirstErrors() public method

Defined in: yii\base\Model::getFirstErrors()

傳回模型中每個屬性的第一個錯誤。

另請參閱

public array getFirstErrors ( )
return array

第一個錯誤。 陣列鍵是屬性名稱,而陣列值是對應的錯誤訊息。 如果沒有錯誤,將傳回空陣列。

                public function getFirstErrors()
{
    if (empty($this->_errors)) {
        return [];
    }
    $errors = [];
    foreach ($this->_errors as $name => $es) {
        if (!empty($es)) {
            $errors[$name] = reset($es);
        }
    }
    return $errors;
}

            
getIsNewRecord() public method

傳回一個值,表示目前的記錄是否為新的。

public boolean getIsNewRecord ( )
return boolean

記錄是否為新的,且在呼叫 save() 時應插入。

                public function getIsNewRecord()
{
    return $this->_oldAttributes === null;
}

            
getIterator() public method

Defined in: yii\base\Model::getIterator()

傳回用於遍歷模型中屬性的迭代器。

此方法是 IteratorAggregate 介面所要求的。

public ArrayIterator getIterator ( )
return ArrayIterator

用於遍歷列表中項目的迭代器。

                #[\ReturnTypeWillChange]
public function getIterator()
{
    $attributes = $this->getAttributes();
    return new ArrayIterator($attributes);
}

            
getOldAttribute() public method

傳回指定名稱屬性的舊值。

如果此記錄是查詢的結果,且屬性未載入,則會傳回 null

另請參閱 hasAttribute()

public mixed getOldAttribute ( $name )
$name string

屬性名稱

return mixed

舊的屬性值。 如果屬性在之前未載入或不存在,則為 null

                public function getOldAttribute($name)
{
    return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
}

            
getOldAttributes() public method

傳回舊的屬性值。

public array getOldAttributes ( )
return array

舊的屬性值(名稱-值配對)

                public function getOldAttributes()
{
    return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
}

            
getOldPrimaryKey() public method

傳回舊的主鍵值。

這是指在執行 find 方法(例如 find()、findOne())後,填充到記錄中的主鍵值。 即使主鍵屬性是手動指定了不同的值,該值仍保持不變。

public mixed getOldPrimaryKey ( $asArray false )
$asArray boolean

是否將主鍵值作為陣列傳回。 如果為 true,則傳回值將是一個陣列,其中欄位名稱作為鍵,欄位值作為值。 如果為 false(預設值),則對於非複合主鍵,將傳回純量值。

return mixed

舊的主鍵值。如果主鍵是複合主鍵或 $asArraytrue,則傳回陣列(欄位名稱 => 欄位值)。否則傳回字串(如果鍵值為 null,則傳回 null)。

throws yii\db\Exception

如果 AR 模型沒有主鍵

                public function getOldPrimaryKey($asArray = false)
{
    $keys = static::primaryKey();
    if (empty($keys)) {
        throw new Exception(get_class($this) . ' does not have a primary key. You should either define a primary key for the corresponding table or override the primaryKey() method.');
    }
    if (!$asArray && count($keys) === 1) {
        return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
    }
    $values = [];
    foreach ($keys as $name) {
        $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
    }
    return $values;
}

            
getPrimaryKey() public method

傳回主鍵值。

public mixed getPrimaryKey ( $asArray false )
$asArray boolean

是否將主鍵值作為陣列傳回。 如果為 true,則傳回值將是一個陣列,其中欄位名稱作為鍵,欄位值作為值。 請注意,對於複合主鍵,無論此參數值為何,都將始終傳回陣列。

return mixed

主鍵值。如果主鍵是複合主鍵或 $asArraytrue,則傳回陣列(欄位名稱 => 欄位值)。否則傳回字串(如果鍵值為 null,則傳回 null)。

                public function getPrimaryKey($asArray = false)
{
    $keys = static::primaryKey();
    if (!$asArray && count($keys) === 1) {
        return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
    }
    $values = [];
    foreach ($keys as $name) {
        $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
    }
    return $values;
}

            
getRelatedRecords() public method

傳回所有已填充的關聯記錄。

另請參閱 getRelation()

public array getRelatedRecords ( )
return array

依關聯名稱索引的關聯記錄陣列。

                public function getRelatedRecords()
{
    return $this->_related;
}

            
getRelation() public method

傳回具有指定名稱的關聯物件。

關聯是由 getter 方法定義的,該方法傳回 yii\db\ActiveQueryInterface 物件。 它可以宣告在 Active Record 類別本身或其行為之一中。

public yii\db\ActiveQueryInterface|yii\db\ActiveQuery|null getRelation ( $name, $throwException true )
$name string

關聯名稱,例如透過 getOrders() 方法定義的關聯的 orders(區分大小寫)。

$throwException boolean

如果關聯不存在是否擲回例外。

return yii\db\ActiveQueryInterface|yii\db\ActiveQuery|null

關聯式查詢物件。 如果關聯不存在且 $throwExceptionfalse,則將傳回 null

throws yii\base\InvalidArgumentException

如果命名的關聯不存在。

                public function getRelation($name, $throwException = true)
{
    $getter = 'get' . $name;
    try {
        // the relation could be defined in a behavior
        $relation = $this->$getter();
    } catch (UnknownMethodException $e) {
        if ($throwException) {
            throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
        }
        return null;
    }
    if (!$relation instanceof ActiveQueryInterface) {
        if ($throwException) {
            throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
        }
        return null;
    }
    if (method_exists($this, $getter)) {
        // relation name is case sensitive, trying to validate it when the relation is defined within this class
        $method = new \ReflectionMethod($this, $getter);
        $realName = lcfirst(substr($method->getName(), 3));
        if ($realName !== $name) {
            if ($throwException) {
                throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
            }
            return null;
        }
    }
    return $relation;
}

            
getScenario() public method

Defined in: yii\base\Model::getScenario()

傳回此模型中使用的情境。

情境會影響驗證的執行方式以及哪些屬性可以大量指派。

public string getScenario ( )
return string

此模型所處的情境。 預設為 SCENARIO_DEFAULT

                public function getScenario()
{
    return $this->_scenario;
}

            
getValidators() public method

定義於: yii\base\Model::getValidators()

傳回在 rules() 中宣告的所有驗證器。

此方法與 getActiveValidators() 不同之處在於,後者僅傳回適用於目前 $scenario 的驗證器。

由於此方法傳回 ArrayObject 物件,您可以透過插入或移除驗證器來操作它 (在模型行為中很有用)。例如,

$model->validators[] = $newValidator;
public ArrayObject|yii\validators\Validator[] getValidators ( )
return ArrayObject|yii\validators\Validator[]

模型中宣告的所有驗證器。

                public function getValidators()
{
    if ($this->_validators === null) {
        $this->_validators = $this->createValidators();
    }
    return $this->_validators;
}

            
hasAttribute() public method

傳回一個值,表示模型是否具有指定名稱的屬性。

public boolean hasAttribute ( $name )
$name string

屬性的名稱

return boolean

模型是否具有指定名稱的屬性。

                public function hasAttribute($name)
{
    return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
}

            
hasErrors() public method

定義於: yii\base\Model::hasErrors()

傳回一個值,表示是否有任何驗證錯誤。

public boolean hasErrors ( $attribute null )
$attribute string|null

屬性名稱。使用 null 以檢查所有屬性。

return boolean

是否有任何錯誤。

                public function hasErrors($attribute = null)
{
    return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
}

            
hasEventHandlers() public method

定義於: 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);
}

            
hasMany() public method

宣告一個 has-many 關聯。

宣告以關聯式 yii\db\ActiveQuery 實例的形式傳回,透過此實例可以查詢和檢索相關記錄。

`has-many` 關聯意味著有多個相關記錄符合此關聯設定的條件,例如,一個客戶有多個訂單。

例如,要為 `Customer` 類別宣告 `orders` 關聯,我們可以在 `Customer` 類別中撰寫以下程式碼

public function getOrders()
{
    return $this->hasMany(Order::class, ['customer_id' => 'id']);
}

請注意,在上面程式碼中,`$link` 參數中的 'customer_id' 鍵指的是相關類別 `Order` 中的屬性名稱,而 'id' 值指的是目前 AR 類別中的屬性名稱。

呼叫在 yii\db\ActiveQuery 中宣告的方法以進一步自訂關聯。

public yii\db\ActiveQueryInterface hasMany ( $class, $link )
$class string

相關記錄的類別名稱

$link array

主鍵-外鍵約束。陣列的鍵指的是與 `$class` 模型關聯的記錄的屬性,而陣列的值指的是 AR 類別中對應的屬性。

return yii\db\ActiveQueryInterface

關聯式查詢物件。

                public function hasMany($class, $link)
{
    return $this->createRelationQuery($class, $link, true);
}

            
hasMethod() public method

定義於: 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;
}

            
hasOne() public method

宣告一個 has-one 關聯。

宣告以關聯式 yii\db\ActiveQuery 實例的形式傳回,透過此實例可以查詢和檢索相關記錄。

`has-one` 關聯意味著最多只有一個相關記錄符合此關聯設定的條件,例如,一個客戶有一個國家。

例如,要為 `Customer` 類別宣告 `country` 關聯,我們可以在 `Customer` 類別中撰寫以下程式碼

public function getCountry()
{
    return $this->hasOne(Country::class, ['id' => 'country_id']);
}

請注意,在上面程式碼中,`$link` 參數中的 'id' 鍵指的是相關類別 `Country` 中的屬性名稱,而 'country_id' 值指的是目前 AR 類別中的屬性名稱。

呼叫在 yii\db\ActiveQuery 中宣告的方法以進一步自訂關聯。

public yii\db\ActiveQueryInterface hasOne ( $class, $link )
$class string

相關記錄的類別名稱

$link array

主鍵-外鍵約束。陣列的鍵指的是與 `$class` 模型關聯的記錄的屬性,而陣列的值指的是 AR 類別中對應的屬性。

return yii\db\ActiveQueryInterface

關聯式查詢物件。

                public function hasOne($class, $link)
{
    return $this->createRelationQuery($class, $link, false);
}

            
hasProperty() public method

定義於: 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);
}

            
init() public method

初始化物件。

此方法在建構函式的末尾呼叫。預設實作將觸發 EVENT_INIT 事件。

public void init ( )

                public function init()
{
    parent::init();
    $this->trigger(self::EVENT_INIT);
}

            
insert() public abstract method

定義於: yii\db\ActiveRecordInterface::insert()

使用此記錄的屬性值將記錄插入資料庫。

使用範例

$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
public abstract boolean insert ( $runValidation true, $attributes null )
$runValidation boolean

是否在儲存記錄之前執行驗證 (呼叫 validate())。預設值為 `true`。如果驗證失敗,記錄將不會儲存到資料庫,且此方法將傳回 `false`。

$attributes array|null

需要儲存的屬性列表。預設值為 `null`,表示將儲存從資料庫載入的所有屬性。

return boolean

屬性是否有效且記錄是否成功插入。

                public function insert($runValidation = true, $attributes = null);

            
instance() public static method

定義於: yii\base\StaticInstanceTrait::instance()

傳回靜態類別實例,可用於取得 meta 資訊。

public static static instance ( $refresh false )
$refresh boolean

即使靜態實例已快取,是否重新建立。

return static

類別實例。

                public static function instance($refresh = false)
{
    $className = get_called_class();
    if ($refresh || !isset(self::$_instances[$className])) {
        self::$_instances[$className] = Yii::createObject($className);
    }
    return self::$_instances[$className];
}

            
instantiate() public static method

建立一個 active record 實例。

此方法與 populateRecord() 一起由 yii\db\ActiveQuery 呼叫。它不適用於直接建立新記錄。

如果正在建立的實例取決於要填入記錄的列資料,您可以覆寫此方法。例如,透過根據欄位的值建立記錄,您可以實作所謂的單表繼承對應。

public static static instantiate ( $row )
$row array

要填入記錄的列資料。

return static

新建立的 active record

                public static function instantiate($row)
{
    return new static();
}

            
isAttributeActive() public method

定義於: yii\base\Model::isAttributeActive()

傳回一個值,表示屬性在目前情境中是否為 active。

另請參閱 activeAttributes()

public boolean isAttributeActive ( $attribute )
$attribute string

屬性名稱

return boolean

屬性在目前情境中是否為作用中

                public function isAttributeActive($attribute)
{
    return in_array($attribute, $this->activeAttributes(), true);
}

            
isAttributeChanged() public method

傳回一個值,表示指定名稱的屬性是否已變更。

public boolean isAttributeChanged ( $name, $identical true )
$name string

屬性的名稱。

$identical boolean

是否使用 `===` 對相同的值進行新舊值的比較,預設值為 `true`。否則,比較時會使用 `==`。此參數自 2.0.4 版起可用。

return boolean

屬性是否已變更

                public function isAttributeChanged($name, $identical = true)
{
    if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
        if ($identical) {
            return $this->_attributes[$name] !== $this->_oldAttributes[$name];
        }
        return $this->_attributes[$name] != $this->_oldAttributes[$name];
    }
    return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
}

            
isAttributeRequired() public method

定義於: yii\base\Model::isAttributeRequired()

傳回一個值,表示屬性是否為必要。

這透過檢查屬性是否與目前 $scenario 中的 required 驗證規則相關聯來判斷。

請注意,當驗證器使用 $when 套用條件式驗證時,無論 `when` 條件為何,此方法都會傳回 `false`,因為它可能會在模型載入資料之前呼叫。

public boolean isAttributeRequired ( $attribute )
$attribute string

屬性名稱

return boolean

屬性是否為必要

                public function isAttributeRequired($attribute)
{
    foreach ($this->getActiveValidators($attribute) as $validator) {
        if ($validator instanceof RequiredValidator && $validator->when === null) {
            return true;
        }
    }
    return false;
}

            
isAttributeSafe() public method

定義於: yii\base\Model::isAttributeSafe()

傳回一個值,表示屬性對於大量賦值是否安全。

另請參閱 safeAttributes()

public boolean isAttributeSafe ( $attribute )
$attribute string

屬性名稱

return boolean

屬性是否適合大量指派

                public function isAttributeSafe($attribute)
{
    return in_array($attribute, $this->safeAttributes(), true);
}

            
isPrimaryKey() public static method

傳回一個值,表示給定的一組屬性是否代表此模型的主鍵。

public static boolean isPrimaryKey ( $keys )
$keys array

要檢查的屬性集

return boolean

給定的屬性集是否代表此模型的主鍵

                public static function isPrimaryKey($keys)
{
    $pks = static::primaryKey();
    if (count($keys) === count($pks)) {
        return count(array_intersect($keys, $pks)) === count($pks);
    }
    return false;
}

            
isRelationPopulated() public method

檢查指定名稱的關聯是否已填充記錄。

另請參閱 getRelation()

public boolean isRelationPopulated ( $name )
$name string

關聯名稱,例如透過 getOrders() 方法定義的關聯的 orders(區分大小寫)。

return boolean

關聯是否已填入記錄。

                public function isRelationPopulated($name)
{
    return array_key_exists($name, $this->_related);
}

            
link() public method

建立兩個模型之間的關聯。

透過將一個模型中的外鍵值設定為另一個模型中對應的主鍵值來建立關聯。具有外鍵的模型將會儲存到資料庫中,不會執行驗證且不會觸發事件/行為。

如果關聯涉及聯結表,則會將包含來自兩個模型的主鍵值的新列插入到聯結表中。

請注意,此方法要求主鍵值不得為 null。

public void link ( $name, $model, $extraColumns = [] )
$name string

關聯的區分大小寫名稱,例如,透過 `getOrders()` 方法定義的關聯的 `orders`。

$model yii\db\ActiveRecordInterface

要與目前模型連結的模型。

$extraColumns array

要儲存到聯結表的額外欄位值。此參數僅適用於涉及聯結表的關聯 (即,使用 yii\db\ActiveRelationTrait::via()yii\db\ActiveQuery::viaTable() 設定的關聯)。

throws yii\base\InvalidCallException

如果方法無法連結兩個模型。

load() public method

定義於: yii\base\Model::load()

使用輸入資料填充模型。

此方法為以下程式碼提供方便的快捷方式

if (isset($_POST['FormName'])) {
    $model->attributes = $_POST['FormName'];
    if ($model->save()) {
        // handle success
    }
}

使用 load() 可以寫成

if ($model->load($_POST) && $model->save()) {
    // handle success
}

`load()` 從模型的 formName() 方法取得 `'FormName'` (您可以覆寫此方法),除非給定 `$formName` 參數。如果表單名稱為空,`load()` 會使用整個 `$data` 填入模型,而不是 `$data['FormName']`。

請注意,要填入的資料會受到 setAttributes() 的安全檢查。

public boolean load ( $data, $formName null )
$data array

要載入的資料陣列,通常為 `$_POST` 或 `$_GET`。

$formName string|null

用於將資料載入模型的表單名稱,不使用表單時為空字串。如果未設定,則會使用 formName()

return boolean

`load()` 是否在 `$data` 中找到預期的表單。

                public function load($data, $formName = null)
{
    $scope = $formName === null ? $this->formName() : $formName;
    if ($scope === '' && !empty($data)) {
        $this->setAttributes($data);
        return true;
    } elseif (isset($data[$scope])) {
        $this->setAttributes($data[$scope]);
        return true;
    }
    return false;
}

            
loadMultiple() public static method

定義於: yii\base\Model::loadMultiple()

使用來自終端使用者的資料填充一組模型。

此方法主要用於收集表格資料輸入。要為每個模型載入的資料為 `$data[formName][index]`,其中 `formName` 指的是 formName() 的值,而 `index` 是 `$models` 陣列中模型的索引。如果 formName() 為空,則會使用 `$data[index]` 填入每個模型。要填入每個模型的資料會受到 setAttributes() 的安全檢查。

public static boolean loadMultiple ( $models, $data, $formName null )
$models array

要填入的模型。請注意,所有模型應具有相同的類別。

$data array

資料陣列。這通常是 `$_POST` 或 `$_GET`,但也可是終端使用者提供的任何有效陣列。

$formName string|null

用於將資料載入模型的表單名稱。如果未設定,則會使用 `$models` 中第一個模型的 formName() 值。此參數自 2.0.1 版起可用。

return boolean

是否至少成功填入其中一個模型。

                public static function loadMultiple($models, $data, $formName = null)
{
    if ($formName === null) {
        /* @var $first Model|false */
        $first = reset($models);
        if ($first === false) {
            return false;
        }
        $formName = $first->formName();
    }
    $success = false;
    foreach ($models as $i => $model) {
        /* @var $model Model */
        if ($formName == '') {
            if (!empty($data[$i]) && $model->load($data[$i], '')) {
                $success = true;
            }
        } elseif (!empty($data[$formName][$i]) && $model->load($data[$formName][$i], '')) {
            $success = true;
        }
    }
    return $success;
}

            
loadRelations() public method (自 2.0.50 版起可用)

為已載入的主模型 eager loads 相關模型。

如果某些相關模型僅在滿足特定條件時才使用,則有助於減少針對資料庫執行的查詢次數。例如

$customer = Customer::find()->where(['id' => 123])->one();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    $customer->loadRelations('orders.items');
}
public void loadRelations ( $relationNames, $asArray false )
$relationNames string|array

要從資料庫載入的此模型的關聯名稱。請參閱 yii\db\ActiveQueryInterface::with() 以了解如何指定此引數。

$asArray boolean

是否將每個關聯載入為陣列或物件 (如果關聯本身未指定)。

                public function loadRelations($relationNames, $asArray = false)
{
    $models = [$this];
    static::loadRelationsFor($models, $relationNames, $asArray);
}

            
loadRelationsFor() public static method (自 2.0.50 版起可用)

為已載入的主模型 eager loads 相關模型。

如果某些相關模型僅在滿足特定條件時才使用,則有助於減少針對資料庫執行的查詢次數。例如

$customers = Customer::find()->where(['country_id' => 123])->all();
if (Yii:app()->getUser()->getIdentity()->canAccessOrders()) {
    Customer::loadRelationsFor($customers, 'orders.items');
}
public static void loadRelationsFor ( &$models, $relationNames, $asArray false )
$models array|yii\db\ActiveRecordInterface[]

主要模型的陣列。每個模型應具有相同的類型,且可以是

$relationNames string|array

要從資料庫載入的主要模型的關聯名稱。請參閱 yii\db\ActiveQueryInterface::with() 以了解如何指定此引數。

$asArray boolean

是否將每個相關模型載入為陣列或物件 (如果關聯本身未指定)。

                public static function loadRelationsFor(&$models, $relationNames, $asArray = false)
{
    // ActiveQueryTrait::findWith() called below assumes $models array is non-empty.
    if (empty($models)) {
        return;
    }
    static::find()->asArray($asArray)->findWith((array)$relationNames, $models);
}

            
markAttributeDirty() public method

將屬性標記為 dirty。

呼叫 update() 時,即使記錄未進行任何變更,也可以呼叫此方法來強制更新記錄。

public void markAttributeDirty ( $name )
$name string

屬性名稱

                public function markAttributeDirty($name)
{
    unset($this->_oldAttributes[$name]);
}

            
off() public method

定義於: 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;
}

            
offsetExists() public method

傳回在指定偏移量處是否存在元素。

此方法為 ArrayAccess 介面所要求。

public boolean offsetExists ( $offset )
$offset mixed

要檢查的偏移量

return boolean

在指定的偏移量處是否有元素。

                #[\ReturnTypeWillChange]
public function offsetExists($offset)
{
    return $this->__isset($offset);
}

            
offsetGet() public method

定義於: yii\base\Model::offsetGet()

傳回指定偏移量處的元素。

此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 `$value = $model[$offset];` 的程式碼時,會隱含地呼叫它。

public mixed offsetGet ( $offset )
$offset string

要檢索元素的偏移量。

return mixed

偏移量處的元素,如果在偏移量處找不到元素,則為 null

                #[\ReturnTypeWillChange]
public function offsetGet($offset)
{
    return $this->$offset;
}

            
offsetSet() public method

定義於: yii\base\Model::offsetSet()

設定指定偏移量處的元素。

此方法為 SPL 介面 ArrayAccess 所要求。當您使用類似 `$model[$offset] = $value;` 的程式碼時,會隱含地呼叫它。

public void offsetSet ( $offset, $value )
$offset string

要設定元素的偏移量

$value mixed

元素值

                #[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
    $this->$offset = $value;
}

            
offsetUnset() public method

將指定偏移量處的元素值設定為 null。

此方法為 SPL 介面 ArrayAccess 所需。當您使用類似 unset($model[$offset]) 的語法時,會隱含地呼叫此方法。

public void offsetUnset ( $offset )
$offset mixed

要取消設定元素的偏移量

                public function offsetUnset($offset)
{
    if (property_exists($this, $offset)) {
        $this->$offset = null;
    } else {
        unset($this->$offset);
    }
}

            
on() public method

定義於: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理器必須是有效的 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 可呼叫

事件處理器

$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]);
    }
}

            
onUnsafeAttribute() public method

定義於: yii\base\Model::onUnsafeAttribute()

當大量賦值不安全屬性時,會調用此方法。

預設實作會在 YII_DEBUG 開啟時記錄警告訊息。否則它不會執行任何操作。

public void onUnsafeAttribute ( $name, $value )
$name string

不安全屬性名稱

$value mixed

屬性值

                public function onUnsafeAttribute($name, $value)
{
    if (YII_DEBUG) {
        Yii::debug("Failed to set unsafe attribute '$name' in '" . get_class($this) . "'.", __METHOD__);
    }
}

            
optimisticLock() public method

傳回儲存鎖定版本以實作 optimistic locking 的欄位名稱。

樂觀鎖定允許多個使用者存取相同的記錄進行編輯,並避免潛在的衝突。當使用者嘗試儲存基於過時資料的記錄時(因為另一個使用者已修改資料),將會拋出 yii\db\StaleObjectException 異常,並且更新或刪除將被跳過。

樂觀鎖定僅由 update()delete() 支援。

要使用樂觀鎖定:

  1. 建立一個欄位來儲存每列的版本號碼。欄位類型應為 BIGINT DEFAULT 0。覆寫此方法以傳回此欄位的名稱。
  2. 在任何更新或刪除之前,請確保版本值已提交並載入到您的模型中。或者將 OptimisticLockBehavior 新增至您的模型類別,以自動化此過程。
  3. 在收集使用者輸入的 Web 表單中,新增一個隱藏欄位,用於儲存正在更新的記錄的鎖定版本。
  4. 在執行資料更新的控制器動作中,嘗試捕獲 yii\db\StaleObjectException 並實作必要的業務邏輯(例如合併變更、提示過時資料)以解決衝突。
public string|null optimisticLock ( )
return string|null

儲存表格列鎖定版本的欄位名稱。如果傳回 null(預設實作),則不支援樂觀鎖定。

                public function optimisticLock()
{
    return null;
}

            
populateRecord() public static method

使用來自資料庫/儲存體的資料列填充 active record 物件。

這是一個內部方法,旨在從資料庫中提取資料後呼叫以建立 active record 物件。它主要由 yii\db\ActiveQuery 用於將查詢結果填充到 active record 中。

手動呼叫此方法時,您應該在建立的記錄上呼叫 afterFind() 以觸發 afterFind Event

public static void populateRecord ( $record, $row )
$record yii\db\BaseActiveRecord

要填充的記錄。在大多數情況下,這將是由 instantiate() 事先建立的實例。

$row array

屬性值(名稱 => 值)

                public static function populateRecord($record, $row)
{
    $columns = array_flip($record->attributes());
    foreach ($row as $name => $value) {
        if (isset($columns[$name])) {
            $record->_attributes[$name] = $value;
        } elseif ($record->canSetProperty($name)) {
            $record->$name = $value;
        }
    }
    $record->_oldAttributes = $record->_attributes;
    $record->_related = [];
    $record->_relationsDependencies = [];
}

            
populateRelation() public method

使用相關記錄填充指定名稱的關聯。

請注意,此方法不會檢查關係是否存在。

另請參閱 getRelation()

public void populateRelation ( $name, $records )
$name string

關聯名稱,例如透過 getOrders() 方法定義的關聯的 orders(區分大小寫)。

$records yii\db\ActiveRecordInterface|array|null

要填充到關係中的相關記錄。

                public function populateRelation($name, $records)
{
    foreach ($this->_relationsDependencies as &$relationNames) {
        unset($relationNames[$name]);
    }
    $this->_related[$name] = $records;
}

            
primaryKey() public abstract static method

定義於: yii\db\ActiveRecordInterface::primaryKey()

傳回此 AR 類別的主鍵名稱

請注意,即使記錄只有一個主鍵,也應該傳回陣列。

有關主鍵,請改為參閱 getPrimaryKey()

public abstract static string[] primaryKey ( )
return string[]

此 AR 類別的主鍵名稱。

                public static function primaryKey();

            
refresh() public method

使用最新的資料重新填充此 active record。

如果重新整理成功,將會觸發 EVENT_AFTER_REFRESH 事件。此事件自 2.0.8 版本起可用。

public boolean refresh ( )
return boolean

該列是否仍然存在於資料庫中。如果為 true,則最新的資料將會填充到此 active record 中。否則,此記錄將保持不變。

                public function refresh()
{
    /* @var $record BaseActiveRecord */
    $record = static::findOne($this->getPrimaryKey(true));
    return $this->refreshInternal($record);
}

            
refreshInternal() protected method (available since version 2.0.13)

使用從新提取的實例取得的最新資料重新填充此 active record。

另請參閱 refresh()

protected boolean refreshInternal ( $record )
$record yii\db\BaseActiveRecord

要從中取得屬性的記錄。

return boolean

重新整理是否成功。

                protected function refreshInternal($record)
{
    if ($record === null) {
        return false;
    }
    foreach ($this->attributes() as $name) {
        $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
    }
    $this->_oldAttributes = $record->_oldAttributes;
    $this->_related = [];
    $this->_relationsDependencies = [];
    $this->afterRefresh();
    return true;
}

            
resolveFields() protected method

定義於: yii\base\ArrayableTrait::resolveFields()

判斷哪些欄位可以由 toArray() 傳回。

此方法將首先從給定的欄位中提取根欄位。然後,它將根據 fields()extraFields() 中宣告的根欄位檢查請求的根欄位,以確定可以傳回哪些欄位。

protected array resolveFields ( array $fields, array $expand )
$fields array

正在請求匯出的欄位

$expand array

正在請求匯出的額外欄位

return array

要匯出的欄位列表。陣列鍵是欄位名稱,而陣列值是相應的物件屬性名稱或傳回欄位值的 PHP 可呼叫物件。

                protected function resolveFields(array $fields, array $expand)
{
    $fields = $this->extractRootFields($fields);
    $expand = $this->extractRootFields($expand);
    $result = [];
    foreach ($this->fields() as $field => $definition) {
        if (is_int($field)) {
            $field = $definition;
        }
        if (empty($fields) || in_array($field, $fields, true)) {
            $result[$field] = $definition;
        }
    }
    if (empty($expand)) {
        return $result;
    }
    foreach ($this->extraFields() as $field => $definition) {
        if (is_int($field)) {
            $field = $definition;
        }
        if (in_array($field, $expand, true)) {
            $result[$field] = $definition;
        }
    }
    return $result;
}

            
rules() public method

定義於: yii\base\Model::rules()

傳回屬性的驗證規則。

驗證規則由 validate() 用於檢查屬性值是否有效。子類別可能會覆寫此方法以宣告不同的驗證規則。

每個規則都是一個具有以下結構的陣列:

[
    ['attribute1', 'attribute2'],
    'validator type',
    'on' => ['scenario1', 'scenario2'],
    //...other parameters...
]

其中:

  • 屬性列表:必要,指定要驗證的屬性陣列,對於單個屬性,您可以傳遞字串;
  • 驗證器類型:必要,指定要使用的驗證器。它可以是內建驗證器名稱、模型類別的方法名稱、匿名函數或驗證器類別名稱。
  • on:可選,指定可以應用驗證規則的 情境 陣列。如果未設定此選項,則該規則將適用於所有情境。
  • 可以指定其他名稱-值對來初始化相應的驗證器屬性。有關可能的屬性,請參閱各個驗證器類別 API。

驗證器可以是擴展 yii\validators\Validator 的類別的物件,也可以是具有以下簽名的模型類別方法(稱為內聯驗證器):

// $params refers to validation parameters given in the rule
function validatorName($attribute, $params)

在上面的程式碼中,$attribute 指的是目前正在驗證的屬性,而 $params 包含驗證器配置選項的陣列,例如 string 驗證器的 max。目前正在驗證的屬性的值可以作為 $this->$attribute 存取。請注意 attribute 之前的 $;這是取得變數 $attribute 的值,並將其用作要存取的屬性的名稱。

Yii 也提供了一組 內建驗證器。每個驗證器都有一個別名,可以在指定驗證規則時使用。

以下是一些範例:

[
    // built-in "required" validator
    [['username', 'password'], 'required'],
    // built-in "string" validator customized with "min" and "max" properties
    ['username', 'string', 'min' => 3, 'max' => 12],
    // built-in "compare" validator that is used in "register" scenario only
    ['password', 'compare', 'compareAttribute' => 'password2', 'on' => 'register'],
    // an inline validator defined via the "authenticate()" method in the model class
    ['password', 'authenticate', 'on' => 'login'],
    // a validator of class "DateRangeValidator"
    ['dateRange', 'DateRangeValidator'],
];

請注意,為了繼承父類別中定義的規則,子類別需要使用諸如 array_merge() 之類的功能將父規則與子規則合併。

另請參閱 scenarios()

public array rules ( )
return array

驗證規則

                public function rules()
{
    return [];
}

            
safeAttributes() public method

定義於: yii\base\Model::safeAttributes()

傳回在目前情境中可以大量賦值的安全屬性名稱。

public string[] safeAttributes ( )
return string[]

安全屬性名稱

                public function safeAttributes()
{
    $scenario = $this->getScenario();
    $scenarios = $this->scenarios();
    if (!isset($scenarios[$scenario])) {
        return [];
    }
    $attributes = [];
    foreach ($scenarios[$scenario] as $attribute) {
        if (
            $attribute !== ''
            && strncmp($attribute, '!', 1) !== 0
            && !in_array('!' . $attribute, $scenarios[$scenario])
        ) {
            $attributes[] = $attribute;
        }
    }
    return $attributes;
}

            
save() public method

儲存目前的記錄。

$isNewRecordtrue 時,此方法將呼叫 insert();當 $isNewRecordfalse 時,將呼叫 update()

例如,要儲存客戶記錄:

$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();
public boolean save ( $runValidation true, $attributeNames null )
$runValidation boolean

是否在儲存記錄之前執行驗證 (呼叫 validate())。預設值為 `true`。如果驗證失敗,記錄將不會儲存到資料庫,且此方法將傳回 `false`。

$attributeNames array|null

需要儲存的屬性名稱列表。預設為 null,表示將儲存從資料庫載入的所有屬性。

return boolean

儲存是否成功(即,是否沒有發生驗證錯誤)。

                public function save($runValidation = true, $attributeNames = null)
{
    if ($this->getIsNewRecord()) {
        return $this->insert($runValidation, $attributeNames);
    }
    return $this->update($runValidation, $attributeNames) !== false;
}

            
scenarios() public method

定義於: yii\base\Model::scenarios()

傳回情境列表和對應的 active 屬性。

活動屬性是在目前情境中需要驗證的屬性。傳回的陣列應採用以下格式:

[
    'scenario1' => ['attribute11', 'attribute12', ...],
    'scenario2' => ['attribute21', 'attribute22', ...],
    ...
]

預設情況下,活動屬性被認為是安全的,可以大量指派。如果屬性不應被大量指派(因此被認為是不安全的),請在屬性前面加上驚嘆號(例如 '!rank')。

此方法的預設實作將傳回在 rules() 宣告中找到的所有情境。名為 SCENARIO_DEFAULT 的特殊情境將包含在 rules() 中找到的所有屬性。每個情境都將與適用於該情境的驗證規則正在驗證的屬性相關聯。

public array scenarios ( )
return array

情境列表和相應的活動屬性。

                public function scenarios()
{
    $scenarios = [self::SCENARIO_DEFAULT => []];
    foreach ($this->getValidators() as $validator) {
        foreach ($validator->on as $scenario) {
            $scenarios[$scenario] = [];
        }
        foreach ($validator->except as $scenario) {
            $scenarios[$scenario] = [];
        }
    }
    $names = array_keys($scenarios);
    foreach ($this->getValidators() as $validator) {
        if (empty($validator->on) && empty($validator->except)) {
            foreach ($names as $name) {
                foreach ($validator->attributes as $attribute) {
                    $scenarios[$name][$attribute] = true;
                }
            }
        } elseif (empty($validator->on)) {
            foreach ($names as $name) {
                if (!in_array($name, $validator->except, true)) {
                    foreach ($validator->attributes as $attribute) {
                        $scenarios[$name][$attribute] = true;
                    }
                }
            }
        } else {
            foreach ($validator->on as $name) {
                foreach ($validator->attributes as $attribute) {
                    $scenarios[$name][$attribute] = true;
                }
            }
        }
    }
    foreach ($scenarios as $scenario => $attributes) {
        if (!empty($attributes)) {
            $scenarios[$scenario] = array_keys($attributes);
        }
    }
    return $scenarios;
}

            
setAttribute() public method

設定指定名稱的屬性值。

另請參閱 hasAttribute()

public void setAttribute ( $name, $value )
$name string

屬性名稱

$value mixed

屬性值。

throws yii\base\InvalidArgumentException

如果指定的屬性不存在。

                public function setAttribute($name, $value)
{
    if ($this->hasAttribute($name)) {
        if (
            !empty($this->_relationsDependencies[$name])
            && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
        ) {
            $this->resetDependentRelations($name);
        }
        $this->_attributes[$name] = $value;
    } else {
        throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
    }
}

            
setAttributes() public method

定義於: yii\base\Model::setAttributes()

以大量方式設定屬性值。

另請參閱

public void setAttributes ( $values, $safeOnly true )
$values array

要指派給模型的屬性值(名稱 => 值)。

$safeOnly boolean

是否應僅對安全屬性進行指派。安全屬性是指與目前 $scenario 中的驗證規則相關聯的屬性。

                public function setAttributes($values, $safeOnly = true)
{
    if (is_array($values)) {
        $attributes = array_flip($safeOnly ? $this->safeAttributes() : $this->attributes());
        foreach ($values as $name => $value) {
            if (isset($attributes[$name])) {
                $this->$name = $value;
            } elseif ($safeOnly) {
                $this->onUnsafeAttribute($name, $value);
            }
        }
    }
}

            
setIsNewRecord() public method

設定表示記錄是否為新的值。

另請參閱 getIsNewRecord()

public void setIsNewRecord ( $value )
$value boolean

記錄是否為新的,且在呼叫 save() 時應插入。

                public function setIsNewRecord($value)
{
    $this->_oldAttributes = $value ? null : $this->_attributes;
}

            
setOldAttribute() public method

設定指定名稱屬性的舊值。

另請參閱 hasAttribute()

public void setOldAttribute ( $name, $value )
$name string

屬性名稱

$value mixed

舊的屬性值。

throws yii\base\InvalidArgumentException

如果指定的屬性不存在。

                public function setOldAttribute($name, $value)
{
    if ($this->canSetOldAttribute($name)) {
        $this->_oldAttributes[$name] = $value;
    } else {
        throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
    }
}

            
setOldAttributes() public method

設定舊的屬性值。

所有現有的舊屬性值都將被丟棄。

public void setOldAttributes ( $values )
$values array|null

要設定的舊屬性值。如果設定為 null,則此記錄被視為新的

                public function setOldAttributes($values)
{
    $this->_oldAttributes = $values;
}

            
setScenario() public method

定義於: yii\base\Model::setScenario()

設定模型的情境。

請注意,此方法不會檢查情境是否存在。方法 validate() 將執行此檢查。

public void setScenario ( $value )
$value string

此模型的場景。

                public function setScenario($value)
{
    $this->_scenario = $value;
}

            
toArray() public method

定義於: yii\base\ArrayableTrait::toArray()

將模型轉換為陣列。

此方法將首先透過呼叫 resolveFields() 來識別要包含在結果陣列中的欄位。然後,它將使用這些欄位將模型轉換為陣列。如果 $recursive 為 true,則任何嵌入式物件也將轉換為陣列。當嵌入式物件是 yii\base\Arrayable 時,它們各自的巢狀欄位將被提取並傳遞給 toArray()

如果模型實作了 yii\web\Linkable 介面,則結果陣列還將具有 _link 元素,該元素引用介面指定的連結列表。

public array toArray ( array $fields = [], array $expand = [], $recursive true )
$fields array

正在請求的欄位。如果為空或包含 '*',則將傳回 fields() 指定的所有欄位。欄位可以是巢狀的,用點 (.) 分隔。例如:item.field.sub-field,$recursive 必須為 true 才能提取巢狀欄位。如果 $recursive 為 false,則只會提取根欄位。

$expand array

正在請求匯出的額外欄位。只會考慮在 extraFields() 中宣告的欄位。展開也可以是巢狀的,用點 (.) 分隔。例如:item.expand1.expand2,$recursive 必須為 true 才能提取巢狀展開。如果 $recursive 為 false,則只會提取根展開。

$recursive boolean

是否遞迴傳回嵌入式物件的陣列表示形式。

return array

物件的陣列表示形式

                public function toArray(array $fields = [], array $expand = [], $recursive = true)
{
    $data = [];
    foreach ($this->resolveFields($fields, $expand) as $field => $definition) {
        $attribute = is_string($definition) ? $this->$definition : $definition($this, $field);
        if ($recursive) {
            $nestedFields = $this->extractFieldsFor($fields, $field);
            $nestedExpand = $this->extractFieldsFor($expand, $field);
            if ($attribute instanceof Arrayable) {
                $attribute = $attribute->toArray($nestedFields, $nestedExpand);
            } elseif ($attribute instanceof \JsonSerializable) {
                $attribute = $attribute->jsonSerialize();
            } elseif (is_array($attribute)) {
                $attribute = array_map(
                    function ($item) use ($nestedFields, $nestedExpand) {
                        if ($item instanceof Arrayable) {
                            return $item->toArray($nestedFields, $nestedExpand);
                        } elseif ($item instanceof \JsonSerializable) {
                            return $item->jsonSerialize();
                        }
                        return $item;
                    },
                    $attribute
                );
            }
        }
        $data[$field] = $attribute;
    }
    if ($this instanceof Linkable) {
        $data['_links'] = Link::serialize($this->getLinks());
    }
    return $recursive ? ArrayHelper::toArray($data) : $data;
}

            
trigger() public method

定義於: 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);
}

            
unlink() public method

摧毀兩個模型之間的關聯。

如果 $deletetrue,則具有關聯性外鍵的模型將會被刪除。否則,外鍵將會被設定為 null,且模型將會在不驗證的情況下儲存。

public void unlink ( $name, $model, $delete false )
$name string

關聯的區分大小寫名稱,例如,透過 `getOrders()` 方法定義的關聯的 `orders`。

$model yii\db\ActiveRecordInterface

要從目前模型取消關聯的模型。您必須確保該模型確實與目前模型相關聯,因為此方法不會檢查此項。

$delete boolean

是否刪除包含外鍵的模型。如果為 false,模型的外鍵將會被設定為 null 並儲存。如果為 true,則包含外鍵的模型將會被刪除。

throws yii\base\InvalidCallException

如果模型無法取消關聯

throws yii\db\Exception
throws yii\db\StaleObjectException

unlinkAll() public method

摧毀目前模型中的關聯。

如果 $deletetrue,則具有關聯性外鍵的模型將會被刪除。否則,外鍵將會被設定為 null,且模型將會在不驗證的情況下儲存。

請注意,為了在不移除記錄的情況下破壞關聯性,請確保您的鍵可以設定為 null

public void unlinkAll ( $name, $delete false )
$name string

關聯的區分大小寫名稱,例如,透過 `getOrders()` 方法定義的關聯的 `orders`。

$delete boolean

是否刪除包含外鍵的模型。

請注意,刪除將會使用 deleteAll() 執行,這將不會在相關模型上觸發任何事件。如果您需要觸發 EVENT_BEFORE_DELETEEVENT_AFTER_DELETE,您需要先 find 模型,然後在它們的每一個上呼叫 delete()

                public function unlinkAll($name, $delete = false)
{
    /* @var $relation ActiveQueryInterface|ActiveQuery */
    $relation = $this->getRelation($name);
    if ($relation->via !== null) {
        if (is_array($relation->via)) {
            /* @var $viaRelation ActiveQuery */
            list($viaName, $viaRelation) = $relation->via;
            $viaClass = $viaRelation->modelClass;
            unset($this->_related[$viaName]);
        } else {
            $viaRelation = $relation->via;
            $viaTable = reset($relation->via->from);
        }
        $condition = [];
        $nulls = [];
        foreach ($viaRelation->link as $a => $b) {
            $nulls[$a] = null;
            $condition[$a] = $this->$b;
        }
        if (!empty($viaRelation->where)) {
            $condition = ['and', $condition, $viaRelation->where];
        }
        if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
            $condition = ['and', $condition, $viaRelation->on];
        }
        if (is_array($relation->via)) {
            /* @var $viaClass ActiveRecordInterface */
            if ($delete) {
                $viaClass::deleteAll($condition);
            } else {
                $viaClass::updateAll($nulls, $condition);
            }
        } else {
            /* @var $viaTable string */
            /* @var $command Command */
            $command = static::getDb()->createCommand();
            if ($delete) {
                $command->delete($viaTable, $condition)->execute();
            } else {
                $command->update($viaTable, $nulls, $condition)->execute();
            }
        }
    } else {
        /* @var $relatedModel ActiveRecordInterface */
        $relatedModel = $relation->modelClass;
        if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
            // relation via array valued attribute
            $this->$b = [];
            $this->save(false);
        } else {
            $nulls = [];
            $condition = [];
            foreach ($relation->link as $a => $b) {
                $nulls[$a] = null;
                $condition[$a] = $this->$b;
            }
            if (!empty($relation->where)) {
                $condition = ['and', $condition, $relation->where];
            }
            if (property_exists($relation, 'on') && !empty($relation->on)) {
                $condition = ['and', $condition, $relation->on];
            }
            if ($delete) {
                $relatedModel::deleteAll($condition);
            } else {
                $relatedModel::updateAll($nulls, $condition);
            }
        }
    }
    unset($this->_related[$name]);
}

            
update() public method

將對此 active record 的變更儲存到相關聯的資料庫表格中。

此方法按順序執行以下步驟

  1. $runValidationtrue 時,呼叫 beforeValidate()。如果 beforeValidate() 回傳 false,則其餘步驟將會被跳過;
  2. $runValidationtrue 時,呼叫 afterValidate()。如果驗證失敗,則其餘步驟將會被跳過;
  3. 呼叫 beforeSave()。如果 beforeSave() 回傳 false,則其餘步驟將會被跳過;
  4. 將記錄儲存到資料庫。如果此步驟失敗,將會跳過其餘步驟;
  5. 呼叫 afterSave()

在上述步驟 1、2、3 和 5 中,事件 EVENT_BEFORE_VALIDATEEVENT_AFTER_VALIDATEEVENT_BEFORE_UPDATEEVENT_AFTER_UPDATE 將會由對應的方法觸發。

只有 變更的屬性值 會被儲存到資料庫中。

例如,要更新客戶記錄

$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();

請注意,更新可能不會影響表格中的任何列。在這種情況下,此方法將會回傳 0。因此,您應該使用以下程式碼來檢查 update() 是否成功。

if ($customer->update() !== false) {
    // update successful
} else {
    // update failed
}
public integer|false update ( $runValidation true, $attributeNames null )
$runValidation boolean

是否在儲存記錄之前執行驗證 (呼叫 validate())。預設值為 `true`。如果驗證失敗,記錄將不會儲存到資料庫,且此方法將傳回 `false`。

$attributeNames array|null

需要儲存的屬性名稱列表。預設為 null,表示將儲存從資料庫載入的所有屬性。

return integer|false

受影響的列數,如果驗證失敗或 beforeSave() 停止更新程序,則為 false

throws yii\db\StaleObjectException

如果啟用 樂觀鎖定,且正在更新的資料已過時。

throws yii\db\Exception

在更新失敗的情況下。

                public function update($runValidation = true, $attributeNames = null)
{
    if ($runValidation && !$this->validate($attributeNames)) {
        return false;
    }
    return $this->updateInternal($attributeNames);
}

            
updateAll() public static method

使用提供的屬性值和條件更新整個表格。

例如,要將所有狀態為 2 的客戶的狀態更改為 1

Customer::updateAll(['status' => 1], 'status = 2');
public static integer updateAll ( $attributes, $condition '' )
$attributes array

要儲存到表格中的屬性值(名稱-值配對)

$condition string|array

將放置在 UPDATE SQL 的 WHERE 部分的條件。請參考 yii\db\Query::where() 了解如何指定此參數。

return integer

更新的列數

throws yii\base\NotSupportedException

如果未被覆寫

                public static function updateAll($attributes, $condition = '')
{
    throw new NotSupportedException(__METHOD__ . ' is not supported.');
}

            
updateAllCounters() public static method

使用提供的計數器變更和條件更新整個表格。

例如,要將所有客戶的年齡增加 1,

Customer::updateAllCounters(['age' => 1]);
public static integer updateAllCounters ( $counters, $condition '' )
$counters array

要更新的計數器(屬性名稱 => 增量值)。如果您想要遞減計數器,請使用負值。

$condition string|array

將放置在 UPDATE SQL 的 WHERE 部分的條件。請參考 yii\db\Query::where() 了解如何指定此參數。

return integer

更新的列數

throws yii\base\NotSupportedException

如果未被覆寫

                public static function updateAllCounters($counters, $condition = '')
{
    throw new NotSupportedException(__METHOD__ . ' is not supported.');
}

            
updateAttributes() public method

更新指定的屬性。

當不需要資料驗證且只需要更新一小部分屬性時,此方法是 update() 的捷徑。

您可以將要更新的屬性指定為名稱列表或名稱-值配對。如果是後者,則將相應地修改屬性值。然後,此方法將會把指定的屬性儲存到資料庫。

請注意,此方法將不會執行資料驗證,也不會觸發事件。

public integer updateAttributes ( $attributes )
$attributes array

要更新的屬性(名稱或名稱-值配對)

return integer

受影響的列數。

                public function updateAttributes($attributes)
{
    $attrs = [];
    foreach ($attributes as $name => $value) {
        if (is_int($name)) {
            $attrs[] = $value;
        } else {
            $this->$name = $value;
            $attrs[] = $name;
        }
    }
    $values = $this->getDirtyAttributes($attrs);
    if (empty($values) || $this->getIsNewRecord()) {
        return 0;
    }
    $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
    foreach ($values as $name => $value) {
        $this->_oldAttributes[$name] = $this->_attributes[$name];
    }
    return $rows;
}

            
updateCounters() public method

更新目前 AR 物件的一個或多個計數器欄位。

請注意,此方法與 updateAllCounters() 的不同之處在於,它僅儲存目前 AR 物件的計數器。

以下是一個範例用法

$post = Post::findOne($id);
$post->updateCounters(['view_count' => 1]);

另請參閱 updateAllCounters()

public boolean updateCounters ( $counters )
$counters array

要更新的計數器(屬性名稱 => 增量值)如果您想要遞減計數器,請使用負值。

return boolean

儲存是否成功

                public function updateCounters($counters)
{
    if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
        foreach ($counters as $name => $value) {
            if (!isset($this->_attributes[$name])) {
                $this->_attributes[$name] = $value;
            } else {
                $this->_attributes[$name] += $value;
            }
            $this->_oldAttributes[$name] = $this->_attributes[$name];
        }
        return true;
    }
    return false;
}

            
updateInternal() protected method

另請參閱 update()

protected integer|false updateInternal ( $attributes null )
$attributes array|null

要更新的屬性

return integer|false

受影響的列數,如果 beforeSave() 停止更新程序,則為 false。

throws yii\db\StaleObjectException

                protected function updateInternal($attributes = null)
{
    if (!$this->beforeSave(false)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if (empty($values)) {
        $this->afterSave(false, $values);
        return 0;
    }
    $condition = $this->getOldPrimaryKey(true);
    $lock = $this->optimisticLock();
    if ($lock !== null) {
        $values[$lock] = $this->$lock + 1;
        $condition[$lock] = $this->$lock;
    }
    // We do not check the return value of updateAll() because it's possible
    // that the UPDATE statement doesn't change anything and thus returns 0.
    $rows = static::updateAll($values, $condition);
    if ($lock !== null && !$rows) {
        throw new StaleObjectException('The object being updated is outdated.');
    }
    if (isset($values[$lock])) {
        $this->$lock = $values[$lock];
    }
    $changedAttributes = [];
    foreach ($values as $name => $value) {
        $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
        $this->_oldAttributes[$name] = $value;
    }
    $this->afterSave(false, $changedAttributes);
    return $rows;
}

            
validate() public method

定義於: yii\base\Model::validate()

執行資料驗證。

此方法會執行適用於目前 $scenario 的驗證規則。以下準則用於判斷規則目前是否適用

  • 規則必須與目前情境相關的屬性相關聯;
  • 規則必須對目前情境有效。

此方法將分別在實際驗證之前和之後呼叫 beforeValidate()afterValidate()。如果 beforeValidate() 回傳 false,則驗證將會被取消,且 afterValidate() 將不會被呼叫。

在驗證期間發現的錯誤可以透過 getErrors()getFirstErrors()getFirstError() 取得。

public boolean validate ( $attributeNames null, $clearErrors true )
$attributeNames string[]|string|null

應該驗證的屬性名稱或屬性名稱列表。如果此參數為空,則表示應該驗證適用驗證規則中列出的任何屬性。

$clearErrors boolean

是否在執行驗證之前呼叫 clearErrors()

return boolean

驗證是否成功且沒有任何錯誤。

throws yii\base\InvalidArgumentException

如果目前情境未知。

                public function validate($attributeNames = null, $clearErrors = true)
{
    if ($clearErrors) {
        $this->clearErrors();
    }
    if (!$this->beforeValidate()) {
        return false;
    }
    $scenarios = $this->scenarios();
    $scenario = $this->getScenario();
    if (!isset($scenarios[$scenario])) {
        throw new InvalidArgumentException("Unknown scenario: $scenario");
    }
    if ($attributeNames === null) {
        $attributeNames = $this->activeAttributes();
    }
    $attributeNames = (array)$attributeNames;
    foreach ($this->getActiveValidators() as $validator) {
        $validator->validateAttributes($this, $attributeNames);
    }
    $this->afterValidate();
    return !$this->hasErrors();
}

            
validateMultiple() public static method

定義於: yii\base\Model::validateMultiple()

驗證多個模型。

此方法將驗證每個模型。正在驗證的模型可以是相同或不同類型。

public static boolean validateMultiple ( $models, $attributeNames null )
$models array

要驗證的模型

$attributeNames array|null

應該驗證的屬性名稱列表。如果此參數為空,則表示應該驗證適用驗證規則中列出的任何屬性。

return boolean

所有模型是否都有效。如果一個或多個模型有驗證錯誤,將會回傳 False。

                public static function validateMultiple($models, $attributeNames = null)
{
    $valid = true;
    /* @var $model Model */
    foreach ($models as $model) {
        $valid = $model->validate($attributeNames) && $valid;
    }
    return $valid;
}

            

事件詳細資訊

隱藏繼承的屬性

EVENT_AFTER_DELETE event of type yii\db\Event

在記錄刪除後觸發的事件。

EVENT_AFTER_FIND event of type yii\db\Event

在記錄建立並使用查詢結果填充後觸發的事件。

EVENT_AFTER_INSERT event of type yii\db\AfterSaveEvent

在記錄插入後觸發的事件。

EVENT_AFTER_REFRESH event of type yii\db\Event (自 2.0.8 版本起可用)

在記錄重新整理後觸發的事件。

EVENT_AFTER_UPDATE event of type yii\db\AfterSaveEvent

在記錄更新後觸發的事件。

EVENT_BEFORE_DELETE event of type yii\base\ModelEvent

在刪除記錄之前觸發的事件。您可以將 yii\base\ModelEvent::$isValid 設定為 false 以停止刪除。

EVENT_BEFORE_INSERT event of type yii\base\ModelEvent

在插入記錄之前觸發的事件。您可以將 yii\base\ModelEvent::$isValid 設定為 false 以停止插入。

EVENT_BEFORE_UPDATE event of type yii\base\ModelEvent

在更新記錄之前觸發的事件。您可以將 yii\base\ModelEvent::$isValid 設定為 false 以停止更新。

EVENT_INIT event of type yii\db\Event

在透過 init() 初始化記錄時觸發的事件。