4 追蹤者

類別 yii\db\ActiveRecord

繼承關係yii\db\ActiveRecord » yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject
實作介面ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface, yii\db\ActiveRecordInterface
使用 Traitsyii\base\ArrayableTrait, yii\base\StaticInstanceTrait
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveRecord.php

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

Active Record 實作了 Active Record 設計模式。Active Record 背後的 premise 是個別的 yii\db\ActiveRecord 物件與資料庫表格中的特定列相關聯。物件的屬性會對應到對應表格的欄位。參照 Active Record 屬性等同於存取該記錄的對應表格欄位。

舉例來說,假設 Customer ActiveRecord 類別與 customer 表格相關聯。這表示類別的 name 屬性會自動對應到 customer 表格中的 name 欄位。感謝 Active Record,假設變數 $customerCustomer 類型的物件,若要取得表格列的 name 欄位值,您可以使用運算式 $customer->name。在本範例中,Active Record 提供物件導向的介面來存取儲存在資料庫中的資料。但 Active Record 提供的功能遠不止於此。

若要宣告 ActiveRecord 類別,您需要擴展 yii\db\ActiveRecord 並實作 tableName 方法

<?php

class Customer extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'customer';
    }
}

tableName 方法只需要傳回與類別相關聯的資料庫表格名稱。

提示:您也可以使用 Gii 程式碼產生器 從您的資料庫表格產生 ActiveRecord 類別。

類別實例可以透過以下兩種方式取得

  • 使用 new 運算子建立新的、空的物件
  • 使用方法從資料庫中提取現有的記錄(或多個記錄)

以下範例顯示 ActiveRecord 的一些典型用法

$user = new User();
$user->name = 'Qiang';
$user->save();  // a new row is inserted into user table

// the following will retrieve the user 'CeBe' from the database
$user = User::find()->where(['name' => 'CeBe'])->one();

// this will get related records from orders table when relation is defined
$orders = $user->orders;

有關 ActiveRecord 的更多詳細資訊和用法,請參閱 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 已變更的屬性值 (name-value pairs)。 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 舊的屬性值 (name-value pairs)。 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

Public Methods

隱藏繼承的方法

Method 描述 定義於
__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\db\ActiveRecord
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() 刪除與此活動記錄對應的資料表列。 yii\db\ActiveRecord
deleteAll() 使用提供的條件刪除資料表中的列。 yii\db\ActiveRecord
detachBehavior() 從組件分離行為。 yii\base\Component
detachBehaviors() 從組件分離所有行為。 yii\base\Component
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此組件。 yii\base\Component
equals() 傳回一個值,指示給定的活動記錄是否與目前的活動記錄相同。 yii\db\ActiveRecord
extraFields() 傳回可以進一步展開並由 toArray() 傳回的欄位列表。 yii\base\ArrayableTrait
fields() 當未指定特定欄位時,傳回預設應由 toArray() 傳回的欄位列表。 yii\base\ArrayableTrait
find() 為查詢目的建立 yii\db\ActiveQueryInterface 實例。 yii\db\ActiveRecord
findAll() 傳回與指定主鍵值或一組欄位值相符的活動記錄模型列表。 yii\db\BaseActiveRecord
findBySql() 使用給定的 SQL 陳述式建立 yii\db\ActiveQuery 實例。 yii\db\ActiveRecord
findOne() 依主鍵或欄位值陣列傳回單一活動記錄模型實例。 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\ActiveRecord
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
getTableSchema() 傳回與此 AR 類別相關聯的 DB 資料表的綱要資訊。 yii\db\ActiveRecord
getValidators() 傳回在 rules() 中宣告的所有驗證器。 yii\base\Model
hasAttribute() 傳回一個值,指示模型是否具有指定名稱的屬性。 yii\db\BaseActiveRecord
hasErrors() 傳回一個值,指示是否存在任何驗證錯誤。 yii\base\Model
hasEventHandlers() 傳回一個值,指示是否有名稱事件附加任何處理常式。 yii\base\Component
hasMany() 有關詳細資訊,請參閱 yii\db\BaseActiveRecord::hasMany() yii\db\ActiveRecord
hasMethod() 傳回一個值,指示是否定義了方法。 yii\base\Component
hasOne() 有關詳細資訊,請參閱 yii\db\BaseActiveRecord::hasOne() yii\db\ActiveRecord
hasProperty() 傳回一個值,指示是否為此組件定義了屬性。 yii\base\Component
init() 初始化物件。 yii\db\BaseActiveRecord
insert() 使用此記錄的屬性值將列插入關聯的資料庫表格。 yii\db\ActiveRecord
instance() 傳回靜態類別實例,可用於取得元資訊。 yii\base\StaticInstanceTrait
instantiate() 建立活動記錄實例。 yii\db\BaseActiveRecord
isAttributeActive() 傳回一個值,指示屬性在目前情境中是否為活動狀態。 yii\base\Model
isAttributeChanged() 傳回一個值,指示指定的屬性是否已變更。 yii\db\BaseActiveRecord
isAttributeRequired() 傳回一個值,指示屬性是否為必要屬性。 yii\base\Model
isAttributeSafe() 傳回一個值,指示屬性對於大量指派是否安全。 yii\base\Model
isPrimaryKey() 傳回一個值,指示給定的屬性集是否代表此模型的主鍵。 yii\db\BaseActiveRecord
isRelationPopulated() 檢查是否已使用記錄填充指定的關聯。 yii\db\BaseActiveRecord
isTransactional() 傳回一個值,指示指定的操作在目前$scenario中是否為事務性的。 yii\db\ActiveRecord
link() 建立兩個模型之間的關係。 yii\db\BaseActiveRecord
load() 使用輸入資料填充模型。 yii\base\Model
loadDefaultValues() 從資料庫表格綱要載入預設值。 yii\db\ActiveRecord
loadMultiple() 使用來自終端使用者的資料填充一組模型。 yii\base\Model
loadRelations() 為已載入的主要模型主動載入關聯模型。 yii\db\BaseActiveRecord
loadRelationsFor() 為主動載入關聯模型已載入的主要模型。 yii\db\BaseActiveRecord
markAttributeDirty() 將屬性標記為髒。 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() 傳回儲存鎖定版本以實作樂觀鎖定的欄位名稱。 yii\db\BaseActiveRecord
populateRecord() 使用來自資料庫/儲存體的資料列填充活動記錄物件。 yii\db\ActiveRecord
populateRelation() 使用關聯記錄填充指定的關聯。 yii\db\BaseActiveRecord
primaryKey() 傳回此 AR 類別的主鍵名稱。 yii\db\ActiveRecord
refresh() 使用最新的資料重新填充此活動記錄。 yii\db\ActiveRecord
rules() 傳回屬性的驗證規則。 yii\base\Model
safeAttributes() 傳回在目前情境中可大量指派的安全屬性名稱。 yii\base\Model
save() 儲存目前的記錄。 yii\db\BaseActiveRecord
scenarios() 傳回情境列表和對應的活動屬性。 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
tableName() 宣告與此 AR 類別相關聯的資料庫表格名稱。 yii\db\ActiveRecord
toArray() 將模型轉換為陣列。 yii\base\ArrayableTrait
transactions() 宣告在不同情境中應在交易中執行的 DB 操作。 yii\db\ActiveRecord
trigger() 觸發事件。 yii\base\Component
unlink() 破壞兩個模型之間的關係。 yii\db\BaseActiveRecord
unlinkAll() 破壞目前模型中的關係。 yii\db\BaseActiveRecord
update() 將對此活動記錄的變更儲存到關聯的資料庫表格中。 yii\db\ActiveRecord
updateAll() 使用提供的屬性值和條件更新整個資料表。 yii\db\ActiveRecord
updateAllCounters() 使用提供的計數器變更和條件更新整個資料表。 yii\db\ActiveRecord
updateAttributes() 更新指定的屬性。 yii\db\BaseActiveRecord
updateCounters() 更新目前 AR 物件的一個或多個計數器欄位。 yii\db\BaseActiveRecord
validate() 執行資料驗證。 yii\base\Model
validateMultiple() 驗證多個模型。 yii\base\Model

Protected Methods

隱藏繼承的方法

Method 描述 定義於
createRelationQuery() has-onehas-many 關聯建立查詢實例。 yii\db\BaseActiveRecord
deleteInternal() 刪除 ActiveRecord,而不考慮交易。 yii\db\ActiveRecord
extractFieldsFor() 從給定根欄位的欄位集合中提取巢狀欄位。巢狀欄位以點 (.) 分隔。例如:"item.id"。先前的範例會提取 "id"。 yii\base\ArrayableTrait
extractRootFields() 從巢狀欄位中提取根欄位名稱。 yii\base\ArrayableTrait
insertInternal() 將 ActiveRecord 插入 DB,而不考慮交易。 yii\db\ActiveRecord
refreshInternal() 使用從新獲取的實例取得的最新資料重新填充此活動記錄。 yii\db\BaseActiveRecord
resolveFields() 決定可以由 toArray() 傳回哪些欄位。 yii\base\ArrayableTrait
updateInternal() yii\db\BaseActiveRecord

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

隱藏繼承的常數

Constant Value 描述 定義於
OP_ALL 0x7 所有三個操作:插入、更新、刪除。這是運算式:OP_INSERT | OP_UPDATE | OP_DELETE 的快捷方式。 yii\db\ActiveRecord
OP_DELETE 0x4 刪除操作。這主要用於覆寫 transactions() 以指定哪些操作是事務性的。 yii\db\ActiveRecord
OP_INSERT 0x1 插入操作。這主要用於覆寫 transactions() 以指定哪些操作是事務性的。 yii\db\ActiveRecord
OP_UPDATE 0x2 更新操作。這主要用於覆寫 transactions() 以指定哪些操作是事務性的。 yii\db\ActiveRecord
SCENARIO_DEFAULT 'default' 預設情境的名稱。 yii\base\Model

Method Details

隱藏繼承的方法

__call() public method

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

呼叫未定義為類別方法的指定名稱方法。

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

不要直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知方法時會隱式呼叫。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

return mixed

方法回傳值

throws yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__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

Defined in: yii\db\BaseActiveRecord::__get()

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

Defined in: yii\db\BaseActiveRecord::__isset()

檢查屬性值是否為 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

Defined in: yii\db\BaseActiveRecord::__set()

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

Defined in: yii\db\BaseActiveRecord::__unset()

將組件屬性設定為 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 array 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

Defined in: yii\db\BaseActiveRecord::afterDelete()

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

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

public void afterDelete ( )

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

            
afterFind() public method

Defined in: yii\db\BaseActiveRecord::afterFind()

當 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)

Defined in: yii\db\BaseActiveRecord::afterRefresh()

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

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

public void afterRefresh ( )

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

            
afterSave() public method

Defined in: yii\db\BaseActiveRecord::afterSave()

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

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

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

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

$changedAttributes array

已變更並儲存的屬性的舊值。您可以使用此參數根據所做的變更採取行動,例如在密碼已變更時發送電子郵件,或實作追蹤所有變更的稽核追蹤。$changedAttributes 提供您舊的屬性值,而活動記錄 ($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 方法

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

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

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

public void afterValidate ( )

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

            
attachBehavior() public 方法

定義於: 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 方法

定義於: 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 方法 (自 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 方法

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

傳回屬性標籤。

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

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

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

另請參閱 generateAttributeLabel()

public array attributeLabels ( )
return array

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

                public function attributeLabels()
{
    return [];
}

            
attributes() public 方法

傳回模型的所有屬性名稱列表。

預設實作將傳回與此 AR 類別關聯的資料表的所有欄位名稱。

public array attributes ( )
return array

屬性名稱列表。

                public function attributes()
{
    return static::getTableSchema()->getColumnNames();
}

            
beforeDelete() public 方法

定義於: yii\db\BaseActiveRecord::beforeDelete()

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

預設實作會引發 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 方法

定義於: yii\db\BaseActiveRecord::beforeSave()

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

預設實作會在 $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 方法

定義於: 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 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::canGetProperty()

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

如果符合以下條件,則可以讀取屬性:

  • 類別具有與指定名稱關聯的 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 方法

定義於: yii\db\BaseActiveRecord::canSetOldAttribute()

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

另請參閱 setOldAttribute()

public boolean canSetOldAttribute ( $name )
$name string

屬性名稱

return boolean

是否可以設定舊的屬性

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

            
canSetProperty() public 方法

定義於: yii\db\BaseActiveRecord::canSetProperty()

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

如果符合以下條件,則可以寫入屬性:

  • 類別具有與指定名稱關聯的 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 方法
自 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 方法

定義於: 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 方法 (自 2.0.12 版本起可用)

定義於: yii\db\BaseActiveRecord::createRelationQuery()

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 方法

定義於: 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 方法

刪除與此活動記錄對應的資料表列。

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

  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 Throwable

在刪除失敗的情況下。

                public function delete()
{
    if (!$this->isTransactional(self::OP_DELETE)) {
        return $this->deleteInternal();
    }
    $transaction = static::getDb()->beginTransaction();
    try {
        $result = $this->deleteInternal();
        if ($result === false) {
            $transaction->rollBack();
        } else {
            $transaction->commit();
        }
        return $result;
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    } catch (\Throwable $e) {
        $transaction->rollBack();
        throw $e;
    }
}

            
deleteAll() public static 方法

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

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

Customer::deleteAll('status = 3');

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

請注意,此方法不會觸發任何事件。如果您需要觸發 EVENT_BEFORE_DELETEEVENT_AFTER_DELETE,您需要先 find 模型,然後在每個模型上呼叫 delete()。例如,上面範例的等效寫法是

$models = Customer::find()->where('status = 3')->all();
foreach ($models as $model) {
    $model->delete();
}

對於大量的模型,您可以考慮使用 yii\db\ActiveQuery::each(),以將記憶體使用量控制在限制範圍內。

public static integer deleteAll ( $condition null, $params = [] )
$condition string|array|null

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

$params array

要繫結到查詢的參數(名稱 => 值)。

return integer

刪除的列數

                public static function deleteAll($condition = null, $params = [])
{
    $command = static::getDb()->createCommand();
    $command->delete(static::tableName(), $condition, $params);
    return $command->execute();
}

            
deleteInternal() protected 方法

刪除 ActiveRecord,而不考慮交易。

protected integer|false deleteInternal ( )
return integer|false

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

throws yii\db\StaleObjectException

                protected function deleteInternal()
{
    if (!$this->beforeDelete()) {
        return false;
    }
    // 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->setOldAttributes(null);
    $this->afterDelete();
    return $result;
}

            
detachBehavior() public 方法

定義於: 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 方法

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

從組件分離所有行為。

public void detachBehaviors ( )

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

            
ensureBehaviors() public 方法

定義於: 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 方法

傳回一個值,指示給定的活動記錄是否與目前的活動記錄相同。

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

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

要比較的記錄

return boolean

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

                public function equals($record)
{
    if ($this->isNewRecord || $record->isNewRecord) {
        return false;
    }
    return static::tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey();
}

            
extraFields() public 方法

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

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

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

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

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

另請參閱

public array extraFields ( )
return array

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

                public function extraFields()
{
    return [];
}

            
extractFieldsFor() protected 方法 (自 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 版本起可用)

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

Defined in: yii\base\ArrayableTrait::fields()

當未指定特定欄位時,傳回預設應由 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 () {
        return $this->first_name . ' ' . $this->last_name;
    },
];

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

此方法的預設實作會傳回以自身索引的 public 物件成員變數。

另請參閱 toArray()

public array fields ( )
return array

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

                public function fields()
{
    $fields = array_keys(Yii::getObjectVars($this));
    return array_combine($fields, $fields);
}

            
find() public static method

為查詢目的建立 yii\db\ActiveQueryInterface 實例。

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

// 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 static yii\db\ActiveQuery find ( )
return yii\db\ActiveQuery

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

                public static function find()
{
    return Yii::createObject(ActiveQuery::className(), [get_called_class()]);
}

            
findAll() public static method

Defined in: yii\db\BaseActiveRecord::findAll()

傳回與指定主鍵值或一組欄位值相符的活動記錄模型列表。

此方法接受

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

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

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

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

// 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 yii\db\BaseActiveRecord[]

ActiveRecord 實例的陣列,如果沒有符合的項目,則為空陣列。

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

            
findBySql() public static method

使用給定的 SQL 陳述式建立 yii\db\ActiveQuery 實例。

請注意,由於 SQL 陳述式已指定,因此在建立的 yii\db\ActiveQuery 實例上呼叫其他查詢修改方法(例如 where()order())將不會有任何效果。但是,呼叫 with()asArray()indexBy() 仍然可以。

以下是一個範例

$customers = Customer::findBySql('SELECT * FROM customer')->all();
public static yii\db\ActiveQuery findBySql ( $sql, $params = [] )
$sql string

要執行的 SQL 陳述式

$params array

在執行期間要繫結到 SQL 陳述式的參數。

return yii\db\ActiveQuery

新建立的 yii\db\ActiveQuery 實例

                public static function findBySql($sql, $params = [])
{
    $query = static::find();
    $query->sql = $sql;
    return $query->params($params);
}

            
findOne() public static method

Defined in: yii\db\BaseActiveRecord::findOne()

依主鍵或欄位值陣列傳回單一活動記錄模型實例。

此方法接受

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

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

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

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

// 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 yii\db\BaseActiveRecord|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,則將傳回模型中 ALL 屬性的驗證器。

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

Defined in: yii\db\BaseActiveRecord::getAttribute()

傳回指定的屬性值。

如果此記錄是查詢的結果,且屬性未載入,則將傳回 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 (自 2.0.4 版本起可用)

Defined in: yii\db\BaseActiveRecord::getAttributeHint()

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

如果屬性看起來像 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

Defined in: yii\db\BaseActiveRecord::getAttributeLabel()

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

屬性可以點號格式指定,以從關聯模型檢索標籤,或允許此模型覆寫關聯模型中定義的標籤。例如,如果屬性指定為 '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 static method

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

預設情況下,"db" 應用程式元件用作資料庫連線。如果您想使用不同的資料庫連線,可以覆寫此方法。

public static yii\db\Connection getDb ( )
return yii\db\Connection

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

                public static function getDb()
{
    return Yii::$app->getDb();
}

            
getDirtyAttributes() public method

Defined in: yii\db\BaseActiveRecord::getDirtyAttributes()

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

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

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 (自 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

Defined in: yii\db\BaseActiveRecord::getIsNewRecord()

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

公開 布林值 getIsNewRecord ( )
return boolean

指示記錄是否為新記錄,並應在呼叫 save() 時插入。

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

            
getIterator() public 方法

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

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

此方法為介面 IteratorAggregate 所需。

公開 ArrayIterator getIterator ( )
return ArrayIterator

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

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

            
getOldAttribute() public 方法

Defined in: yii\db\BaseActiveRecord::getOldAttribute()

傳回指定屬性的舊值。

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

另請參閱 hasAttribute()

公開 mixed getOldAttribute ( $name )
$name string

屬性名稱

return mixed

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

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

            
getOldAttributes() public 方法

Defined in: yii\db\BaseActiveRecord::getOldAttributes()

傳回舊的屬性值。

公開 array getOldAttributes ( )
return array

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

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

            
getOldPrimaryKey() public 方法

Defined in: yii\db\BaseActiveRecord::getOldPrimaryKey()

傳回舊的主鍵值。

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

公開 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 方法

Defined in: yii\db\BaseActiveRecord::getPrimaryKey()

傳回主鍵值。

公開 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 方法

Defined in: yii\db\BaseActiveRecord::getRelatedRecords()

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

另請參閱 getRelation()

公開 array getRelatedRecords ( )
return array

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

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

            
getRelation() public 方法

Defined in: yii\db\BaseActiveRecord::getRelation()

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

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

公開 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 方法

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

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

場景會影響驗證的執行方式以及哪些屬性可以大量賦值。

公開 string getScenario ( )
return string

此模型所處的場景。預設為 SCENARIO_DEFAULT

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

            
getTableSchema() public static 方法

傳回與此 AR 類別相關聯的 DB 資料表的綱要資訊。

public static yii\db\TableSchema getTableSchema ( )
return yii\db\TableSchema

與此 AR 類別關聯的資料庫表格的結構描述資訊。

throws yii\base\InvalidConfigException

如果 AR 類別的表格不存在。

                public static function getTableSchema()
{
    $tableSchema = static::getDb()
        ->getSchema()
        ->getTableSchema(static::tableName());
    if ($tableSchema === null) {
        throw new InvalidConfigException('The table does not exist: ' . static::tableName());
    }
    return $tableSchema;
}

            
getValidators() public 方法

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

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

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

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

$model->validators[] = $newValidator;
公開 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 方法

Defined in: yii\db\BaseActiveRecord::hasAttribute()

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

公開 布林值 hasAttribute ( $name )
$name string

屬性的名稱

return boolean

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

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

            
hasErrors() public 方法

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

傳回一個值,指示是否存在任何驗證錯誤。

公開 布林值 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 方法

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

傳回一個值,指示是否有名稱事件附加任何處理常式。

公開 布林值 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 方法

有關詳細資訊,請參閱 yii\db\BaseActiveRecord::hasMany()

公開 yii\db\ActiveQuery hasMany ( $class, array $link )
$class
$link
return yii\db\ActiveQuery
hasMethod() public 方法

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

傳回一個值,指示是否定義了方法。

如果滿足以下條件,則定義了方法:

  • 類別具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 $checkBehaviors 為 true 時)。
公開 布林值 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 方法

有關詳細資訊,請參閱 yii\db\BaseActiveRecord::hasOne()

公開 yii\db\ActiveQuery hasOne ( $class, array $link )
$class
$link
return yii\db\ActiveQuery
hasProperty() public 方法

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

傳回一個值,指示是否為此組件定義了屬性。

如果滿足以下條件,則定義了屬性:

  • 類別具有與指定名稱關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有帶有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

另請參閱

公開 布林值 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 方法

Defined in: yii\db\BaseActiveRecord::init()

初始化物件。

此方法在建構子結束時呼叫。預設實作將觸發 EVENT_INIT 事件。

公開 void init ( )

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

            
insert() public 方法

使用此記錄的屬性值將列插入關聯的資料庫表格。

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

  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_INSERTEVENT_AFTER_INSERT 將由對應的方法引發。

只有 已變更的屬性值 將被插入資料庫。

如果表格的主鍵是自動遞增的,並且在插入期間為 null,則在插入後將會填入實際值。

例如,要插入客戶記錄

$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
公開 布林值 insert ( $runValidation true, $attributes null )
$runValidation boolean

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

$attributes array|null

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

return boolean

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

throws Throwable

在插入失敗的情況下。

                public function insert($runValidation = true, $attributes = null)
{
    if ($runValidation && !$this->validate($attributes)) {
        Yii::info('Model not inserted due to validation error.', __METHOD__);
        return false;
    }
    if (!$this->isTransactional(self::OP_INSERT)) {
        return $this->insertInternal($attributes);
    }
    $transaction = static::getDb()->beginTransaction();
    try {
        $result = $this->insertInternal($attributes);
        if ($result === false) {
            $transaction->rollBack();
        } else {
            $transaction->commit();
        }
        return $result;
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    } catch (\Throwable $e) {
        $transaction->rollBack();
        throw $e;
    }
}

            
insertInternal() protected 方法

將 ActiveRecord 插入 DB,而不考慮交易。

protected 布林值 insertInternal ( $attributes null )
$attributes array|null

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

return boolean

記錄是否成功插入。

                protected function insertInternal($attributes = null)
{
    if (!$this->beforeSave(true)) {
        return false;
    }
    $values = $this->getDirtyAttributes($attributes);
    if (($primaryKeys = static::getDb()->schema->insert(static::tableName(), $values)) === false) {
        return false;
    }
    foreach ($primaryKeys as $name => $value) {
        $id = static::getTableSchema()->columns[$name]->phpTypecast($value);
        $this->setAttribute($name, $id);
        $values[$name] = $id;
    }
    $changedAttributes = array_fill_keys(array_keys($values), null);
    $this->setOldAttributes($values);
    $this->afterSave(true, $changedAttributes);
    return true;
}

            
instance() public static 方法

Defined in: yii\base\StaticInstanceTrait::instance()

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

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

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

return yii\db\ActiveRecord

類別實例。

                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 方法

Defined in: yii\db\BaseActiveRecord::instantiate()

建立活動記錄實例。

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

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

public static static instantiate ( $row )
$row array

要填入記錄的資料列資料。

return yii\db\BaseActiveRecord

新建立的 active record

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

            
isAttributeActive() public 方法

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

傳回一個值,指示屬性在目前情境中是否為活動狀態。

另請參閱 activeAttributes()

公開 布林值 isAttributeActive ( $attribute )
$attribute string

屬性名稱

return boolean

屬性在目前場景中是否為活動狀態

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

            
isAttributeChanged() public 方法

Defined in: yii\db\BaseActiveRecord::isAttributeChanged()

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

公開 布林值 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 方法

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

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

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

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

公開 布林值 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 方法

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

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

另請參閱 safeAttributes()

公開 布林值 isAttributeSafe ( $attribute )
$attribute string

屬性名稱

return boolean

屬性對於大量賦值是否安全

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

            
isPrimaryKey() public static 方法

Defined in: yii\db\BaseActiveRecord::isPrimaryKey()

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

public static 布林值 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 方法

定義於: yii\db\BaseActiveRecord::isRelationPopulated()

檢查是否已使用記錄填充指定的關聯。

另請參閱 getRelation()

public boolean isRelationPopulated ( $name )
$name string

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

return boolean

關聯是否已填充記錄。

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

            
isTransactional() public 方法

傳回一個值,指示指定的操作在目前$scenario中是否為事務性的。

public boolean isTransactional ( $operation )
$operation integer

要檢查的操作。可能的值為 OP_INSERTOP_UPDATEOP_DELETE

return boolean

指定的運算在目前的 $scenario 中是否為事務性的。

                public function isTransactional($operation)
{
    $scenario = $this->getScenario();
    $transactions = $this->transactions();
    return isset($transactions[$scenario]) && ($transactions[$scenario] & $operation);
}

            
link() public 方法

定義於: yii\db\BaseActiveRecord::link()

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

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

如果關聯涉及連接表,則將在連接表中插入一個新行,其中包含來自兩個模型的主鍵值。

請注意,此方法要求主鍵值不得為 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 方法

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

            
loadDefaultValues() public 方法

從資料庫表格綱要載入預設值。

您可以在建立新實例後呼叫此方法來載入預設值

// class Customer extends \yii\db\ActiveRecord
$customer = new Customer();
$customer->loadDefaultValues();
public $this loadDefaultValues ( $skipIfSet true )
$skipIfSet boolean

是否應保留現有值。這只會為 null 的屬性設定預設值。

return $this

模型實例本身。

                public function loadDefaultValues($skipIfSet = true)
{
    $columns = static::getTableSchema()->columns;
    foreach ($this->attributes() as $name) {
        if (isset($columns[$name])) {
            $defaultValue = $columns[$name]->defaultValue;
            if ($defaultValue !== null && (!$skipIfSet || $this->getAttribute($name) === null)) {
                $this->setAttribute($name, $defaultValue);
            }
        }
    }
    return $this;
}

            
loadMultiple() public static 方法

定義於: 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 方法 (自 2.0.50 版本起可用)

定義於: yii\db\BaseActiveRecord::loadRelations()

為已載入的主要模型主動載入關聯模型。

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

$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 方法 (自 2.0.50 版本起可用)

定義於: yii\db\BaseActiveRecord::loadRelationsFor()

為主動載入關聯模型已載入的主要模型。

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

$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[]

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

  • 一個 active record 實例;
  • 由陣列表示的 active record 實例(即,使用 yii\db\ActiveQuery::asArray() 載入的 active record)。
$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 方法

定義於: yii\db\BaseActiveRecord::markAttributeDirty()

將屬性標記為髒。

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

public void markAttributeDirty ( $name )
$name string

屬性名稱

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

            
off() public 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::offsetExists()

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

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

public boolean offsetExists ( $offset )
$offset mixed

要檢查的偏移量

return boolean

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

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

            
offsetGet() public 方法

定義於: 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 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::offsetUnset()

將指定偏移量處的元素值設定為 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 方法

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

事件處理常式

$data mixed

在觸發事件時要傳遞給事件處理常式的資料。當呼叫事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。

$append boolean

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新處理常式將插入到現有處理常式列表的開頭。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
onUnsafeAttribute() public 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::optimisticLock()

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

樂觀鎖定允許多個使用者存取相同的記錄進行編輯,並避免潛在的衝突。當使用者嘗試儲存基於某些陳舊資料的記錄時(因為另一個使用者已修改資料),將會拋出 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 方法

使用來自資料庫/儲存體的資料列填充活動記錄物件。

這是一個內部方法,旨在在從資料庫擷取資料後呼叫以建立 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 = static::getTableSchema()->columns;
    foreach ($row as $name => $value) {
        if (isset($columns[$name])) {
            $row[$name] = $columns[$name]->phpTypecast($value);
        }
    }
    parent::populateRecord($record, $row);
}

            
populateRelation() public 方法

定義於: yii\db\BaseActiveRecord::populateRelation()

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

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

另請參閱 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 static 方法

傳回此 AR 類別的主鍵名稱。

預設實作將傳回與此 AR 類別關聯的資料庫表中宣告的主鍵。

如果資料庫表未宣告任何主鍵,您應覆寫此方法以傳回您想要用作此 AR 類別主鍵的屬性。

請注意,即使對於具有單一主鍵的表,也應傳回陣列。

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

關聯資料庫表的主鍵。

                public static function primaryKey()
{
    return static::getTableSchema()->primaryKey;
}

            
refresh() public 方法

使用最新的資料重新填充此活動記錄。

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

public boolean refresh ( )
return boolean

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

                public function refresh()
{
    $query = static::find();
    $tableName = key($query->getTablesUsedInFrom());
    $pk = [];
    // disambiguate column names in case ActiveQuery adds a JOIN
    foreach ($this->getPrimaryKey(true) as $key => $value) {
        $pk[$tableName . '.' . $key] = $value;
    }
    $query->where($pk);
    /* @var $record BaseActiveRecord */
    $record = $query->noCache()->one();
    return $this->refreshInternal($record);
}

            
refreshInternal() protected 方法 (自版本 2.0.13 起可用)

定義於: yii\db\BaseActiveRecord::refreshInternal()

使用從新獲取的實例取得的最新資料重新填充此活動記錄。

另請參閱 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 方法

定義於: 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 方法

定義於: 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 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::save()

儲存目前的記錄。

$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 方法

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

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

作用中屬性是在目前情境中要進行驗證的屬性。回傳的陣列應採用以下格式

[
    '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 方法

定義於: yii\db\BaseActiveRecord::setAttribute()

設定指定的屬性值。

另請參閱 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 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::setIsNewRecord()

設定一個值,指示記錄是否為新記錄。

另請參閱 getIsNewRecord()

public void setIsNewRecord ( $value )
$value boolean

指示記錄是否為新記錄,並應在呼叫 save() 時插入。

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

            
setOldAttribute() public 方法

定義於: yii\db\BaseActiveRecord::setOldAttribute()

設定指定屬性的舊值。

另請參閱 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 方法

定義於: yii\db\BaseActiveRecord::setOldAttributes()

設定舊的屬性值。

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

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

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

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

            
setScenario() public 方法

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

設定模型的情境。

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

public void setScenario ( $value )
$value string

此模型所處的情境。

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

            
tableName() public static 方法

宣告與此 AR 類別相關聯的資料庫表格名稱。

預設情況下,此方法透過呼叫 yii\helpers\Inflector::camel2id() 並加上字首 yii\db\Connection::$tablePrefix,將類別名稱作為資料表名稱回傳。例如,如果 yii\db\Connection::$tablePrefixtbl_,則 Customer 變成 tbl_customer,而 OrderItem 變成 tbl_order_item。如果資料表不是按照此慣例命名,您可以覆寫此方法。

public static string tableName ( )
return string

資料表名稱

                public static function tableName()
{
    return '{{%' . Inflector::camel2id(StringHelper::basename(get_called_class()), '_') . '}}';
}

            
toArray() public 方法

定義於: 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() 中宣告的欄位。Expand 也可以是巢狀的,並以點 (.) 分隔。例如:item.expand1.expand2 $recursive 必須為 true 才能提取巢狀 expand。如果 $recursive 為 false,則僅提取根 expand。

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

            
transactions() public 方法

宣告在不同情境中應在交易中執行的 DB 操作。

支援的資料庫操作為:OP_INSERTOP_UPDATEOP_DELETE,它們分別對應於 insert()update()delete() 方法。預設情況下,這些方法不包含在資料庫交易中。

在某些情境中,為了確保資料一致性,您可能希望將其中一些或全部包含在交易中。您可以透過覆寫此方法並回傳需要交易的操作來做到這一點。例如,

return [
    'admin' => self::OP_INSERT,
    'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE,
    // the above is equivalent to the following:
    // 'api' => self::OP_ALL,

];

上述宣告指定在「admin」情境中,插入操作 (insert()) 應在交易中完成;而在「api」情境中,所有操作都應在交易中完成。

public array transactions ( )
return array

交易操作的宣告。陣列鍵是情境名稱,而陣列值是對應的交易操作。

                public function transactions()
{
    return [];
}

            
trigger() public 方法

定義於: 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 方法

定義於: yii\db\BaseActiveRecord::unlink()

破壞兩個模型之間的關係。

如果 $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 方法

定義於: yii\db\BaseActiveRecord::unlinkAll()

破壞目前模型中的關係。

如果 $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 方法

將對此活動記錄的變更儲存到關聯的資料庫表格中。

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

  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 Throwable

在更新失敗的情況下。

                public function update($runValidation = true, $attributeNames = null)
{
    if ($runValidation && !$this->validate($attributeNames)) {
        Yii::info('Model not updated due to validation error.', __METHOD__);
        return false;
    }
    if (!$this->isTransactional(self::OP_UPDATE)) {
        return $this->updateInternal($attributeNames);
    }
    $transaction = static::getDb()->beginTransaction();
    try {
        $result = $this->updateInternal($attributeNames);
        if ($result === false) {
            $transaction->rollBack();
        } else {
            $transaction->commit();
        }
        return $result;
    } catch (\Exception $e) {
        $transaction->rollBack();
        throw $e;
    } catch (\Throwable $e) {
        $transaction->rollBack();
        throw $e;
    }
}

            
updateAll() public static 方法

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

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

Customer::updateAll(['status' => 1], 'status = 2');

警告:如果您未指定任何條件,此方法將更新資料表中的所有列。

請注意,此方法不會觸發任何事件。如果您需要觸發 EVENT_BEFORE_UPDATEEVENT_AFTER_UPDATE,您需要先 find 模型,然後對每個模型呼叫 update()。例如,上面範例的等效寫法為

$models = Customer::find()->where('status = 2')->all();
foreach ($models as $model) {
    $model->status = 1;
    $model->update(false); // skipping validation as no user input is involved
}

對於大量的模型,您可以考慮使用 yii\db\ActiveQuery::each(),以將記憶體使用量控制在限制範圍內。

public static integer updateAll ( $attributes, $condition '', $params = [] )
$attributes array

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

$condition string|array

將放置在 UPDATE SQL 的 WHERE 部分中的條件。有關如何指定此參數,請參閱 yii\db\Query::where()

$params array

要繫結到查詢的參數(名稱 => 值)。

return integer

更新的列數

                public static function updateAll($attributes, $condition = '', $params = [])
{
    $command = static::getDb()->createCommand();
    $command->update(static::tableName(), $attributes, $condition, $params);
    return $command->execute();
}

            
updateAllCounters() public static 方法

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

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

Customer::updateAllCounters(['age' => 1]);

請注意,此方法不會觸發任何事件。

public static integer updateAllCounters ( $counters, $condition '', $params = [] )
$counters array

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

$condition string|array

將放置在 UPDATE SQL 的 WHERE 部分中的條件。有關如何指定此參數,請參閱 yii\db\Query::where()

$params array

要繫結到查詢的參數(名稱 => 值)。請勿將參數命名為 :bp0:bp1 等,因為它們由此方法在內部使用。

return integer

更新的列數

                public static function updateAllCounters($counters, $condition = '', $params = [])
{
    $n = 0;
    foreach ($counters as $name => $value) {
        $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
        $n++;
    }
    $command = static::getDb()->createCommand();
    $command->update(static::tableName(), $counters, $condition, $params);
    return $command->execute();
}

            
updateAttributes() public 方法

定義於: yii\db\BaseActiveRecord::updateAttributes()

更新指定的屬性。

當不需要資料驗證且只需要更新一小組屬性時,此方法是 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

定義於: yii\db\BaseActiveRecord::updateCounters()

更新目前 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
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;
}