Skip to content

StructureElement ​

Type
Class
Namespace
craft\records
Inherits
craft\records\StructureElement » craft\db\ActiveRecord » yii\db\ActiveRecord » yii\db\BaseActiveRecord » yii\base\Model » yii\base\Component » yii\base\BaseObject
Implements
ArrayAccess, IteratorAggregate, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface, yii\db\ActiveRecordInterface
Uses traits
yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
Since
3.0.0

Class StructureElement record.

View source

Public Properties ​

PropertyDescription
activeValidatorsyii\validators\Validator – The validators applicable to the current scenario.
attributesarray – Attribute values (name => value).
behaviorsyii\base\Behavior – List of behaviors attached to this component.
dateCreatedstring – Date created
dateUpdatedstring – Date updated
dirtyAttributesarray – The changed attribute values (name-value pairs).
elementcraft\records\Element – Element
elementIdinteger – Element ID
errorsarray – Errors for all attributes or the specified attribute.
firstErrorsarray – The first errors.
idinteger – ID
isNewRecordboolean – Whether the record is new and should be inserted when calling save().
iteratorArrayIterator – An iterator for traversing the items in the list.
levelinteger – Level
lftinteger – Lft
oldAttributesarray – The old attribute values (name-value pairs).
oldPrimaryKeymixed – The old primary key value.
primaryKeymixed – The primary key value.
relatedRecordsarray – An array of related records indexed by relation names.
rgtinteger – Rgt
rootinteger – Root
scenariostring – The scenario that this model is in.
structurecraft\records\Structure – Structure
structureIdinteger – Structure ID
uidstring – UUID
validatorsArrayObject, yii\validators\Validator – All the validators declared in the model.

element ​

Type
craft\records\Element
Default value
null

Element

View source

elementId ​

Type
integer
Default value
null

Element ID

View source

id ​

Type
integer
Default value
null

ID

View source

level ​

Type
integer
Default value
null

Level

View source

lft ​

Type
integer
Default value
null

Lft

View source

rgt ​

Type
integer
Default value
null

Rgt

View source

root ​

Type
integer
Default value
null

Root

View source

structure ​

Type
craft\records\Structure
Default value
null

Structure

View source

structureId ​

Type
integer
Default value
null

Structure ID

View source

Public Methods ​

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()Constructor.
__get()PHP getter magic method.
__isset()Checks if a property value is null.
__set()PHP setter magic method.
__unset()Sets a component property to be null.
activeAttributes()Returns the attribute names that are subject to validation in the current scenario.
addError()Adds a new error to the specified attribute.
addErrors()Adds a list of errors.
afterDelete()This method is invoked after deleting a record.
afterFind()This method is called when the AR object is created and populated with the query result.
afterRefresh()This method is called when the AR object is refreshed.
afterSave()This method is called at the end of inserting or updating a record.
afterValidate()This method is invoked after validation ends.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attributeHints()Returns the attribute hints.
attributeLabels()Returns the attribute labels.
attributes()Returns the list of all attribute names of the model.
beforeDelete()This method is invoked before deleting a record.
beforeSave()This method is called at the beginning of inserting or updating a record.
beforeValidate()This method is invoked before validation starts.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
className()Returns the fully qualified name of this class.
clearErrors()Removes errors for all attributes or a single attribute.
createValidators()Creates validator objects based on the validation rules specified in rules().
delete()Deletes the table row corresponding to this active record.
deleteAll()Deletes rows in the table using the provided conditions.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
equals()Returns a value indicating whether the given active record is the same as the current one.
extraFields()Returns the list of fields that can be expanded further and returned by toArray().
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
find()Creates an yii\db\ActiveQueryInterface instance for query purpose.
findAll()Returns a list of active record models that match the specified primary key value(s) or a set of column values.
findBySql()See yii\db\ActiveRecord::findBySql() for more info.
findOne()Returns a single active record model instance by a primary key or an array of column values.
formName()Returns the form name that this model class should use.
generateAttributeLabel()Generates a user friendly attribute label based on the give attribute name.
getActiveValidators()Returns the validators applicable to the current scenario.
getAttribute()Returns the named attribute value.
getAttributeHint()Returns the text hint for the specified attribute.
getAttributeLabel()Returns the text label for the specified attribute.
getAttributes()Returns attribute values.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getDb()Returns the database connection used by this AR class.
getDirtyAttributes()Returns the attribute values that have been modified since they are loaded or saved most recently.
getElement()Returns the structure element’s element.
getErrorSummary()Returns the errors for all attributes as a one-dimensional array.
getErrors()Returns the errors for all attributes or a single attribute.
getFirstError()Returns the first error of the specified attribute.
getFirstErrors()Returns the first error of every attribute in the model.
getIsNewRecord()Returns a value indicating whether the current record is new.
getIterator()Returns an iterator for traversing the attributes in the model.
getOldAttribute()Returns the old value of the named attribute.
getOldAttributes()Returns the old attribute values.
getOldPrimaryKey()Returns the old primary key value(s).
getPrimaryKey()Returns the primary key value(s).
getRelatedRecords()Returns all populated related records.
getRelation()Returns the relation object with the specified name.
getScenario()Returns the scenario that this model is used in.
getStructure()Returns the structure element’s structure.
getTableSchema()Returns the schema information of the DB table associated with this AR class.
getValidators()Returns all the validators declared in rules().
hasAttribute()Returns a value indicating whether the model has an attribute with the specified name.
hasErrors()Returns a value indicating whether there is any validation error.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMany()See yii\db\BaseActiveRecord::hasMany() for more info.
hasMethod()Returns a value indicating whether a method is defined.
hasOne()See yii\db\BaseActiveRecord::hasOne() for more info.
hasProperty()Returns a value indicating whether a property is defined for this component.
init()Initializes the object.
insert()Inserts a row into the associated database table using the attribute values of this record.
instance()Returns static class instance, which can be used to obtain meta information.
instantiate()Creates an active record instance.
isAttributeActive()Returns a value indicating whether the attribute is active in the current scenario.
isAttributeChanged()Returns a value indicating whether the named attribute has been changed.
isAttributeRequired()Returns a value indicating whether the attribute is required.
isAttributeSafe()Returns a value indicating whether the attribute is safe for massive assignments.
isPrimaryKey()Returns a value indicating whether the given set of attributes represents the primary key for this model.
isRelationPopulated()Check whether the named relation has been populated with records.
isTransactional()Returns a value indicating whether the specified operation is transactional in the current scenario.
link()Establishes the relationship between two models.
load()Populates the model with input data.
loadDefaultValues()Loads default values from database table schema.
loadMultiple()Populates a set of models with the data from end user.
markAttributeDirty()Marks an attribute dirty.
off()Detaches an existing event handler from this component.
offsetExists()Returns whether there is an element at the specified offset.
offsetGet()Returns the element at the specified offset.
offsetSet()Sets the element at the specified offset.
offsetUnset()Sets the element value at the specified offset to null.
on()Attaches an event handler to an event.
onUnsafeAttribute()This method is invoked when an unsafe attribute is being massively assigned.
optimisticLock()Returns the name of the column that stores the lock version for implementing optimistic locking.
populateRecord()Populates an active record object using a row of data from the database/storage.
populateRelation()Populates the named relation with the related records.
primaryKey()Returns the primary key name(s) for this AR class.
refresh()Repopulates this active record with the latest data.
rules()Returns the validation rules for attributes.
safeAttributes()Returns the attribute names that are safe to be massively assigned in the current scenario.
save()Saves the current record.
scenarios()Returns a list of scenarios and the corresponding active attributes.
setAttribute()Sets the named attribute value.
setAttributes()Sets the attribute values in a massive way.
setIsNewRecord()Sets the value indicating whether the record is new.
setOldAttribute()Sets the old value of the named attribute.
setOldAttributes()Sets the old attribute values.
setScenario()Sets the scenario for the model.
tableName()Declares the name of the database table associated with this AR class.
toArray()Converts the model into an array.
transactions()Declares which DB operations should be performed within a transaction in different scenarios.
trigger()Triggers an event.
unlink()Destroys the relationship between two models.
unlinkAll()Destroys the relationship in current model.
update()Saves the changes to this active record into the associated database table.
updateAll()Updates the whole table using the provided attribute values and conditions.
updateAllCounters()Updates the whole table using the provided counter changes and conditions.
updateAttributes()Updates the specified attributes.
updateCounters()Updates one or several counter columns for the current AR object.
validate()Performs the data validation.
validateMultiple()Validates multiple models.

behaviors() ​

Since
3.4.0

Returns a list of behaviors that this component should behave as.

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

php
'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from \craft\records\Behavior. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using getBehavior() or be detached using detachBehavior(). Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

View source

Returns ​

array – The behavior configurations.

find() ​

Creates an yii\db\ActiveQueryInterface instance for query purpose.

The returned yii\db\ActiveQueryInterface instance can be further customized by calling methods defined in yii\db\ActiveQueryInterface before one() or all() is called to return populated ActiveRecord instances. For example,

php
// 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();

This method is also called by yii\db\BaseActiveRecord::hasOne() and yii\db\BaseActiveRecord::hasMany() to create a relational query.

You may override this method to return a customized query. For example,

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

The following code shows how to apply a default condition for all queries:

php
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();




[View source](https://github.com/craftcms/cms/blob/3.9.14/src/records/StructureElement.php#L60-L63)



#### Returns

[craft\db\StructuredElementQuery](craft-db-structuredelementquery.md) – The newly created `\craft\records\ActiveQuery` instance.



### `getElement()` {#method-getelement}





Returns the structure element’s element.




[View source](https://github.com/craftcms/cms/blob/3.9.14/src/records/StructureElement.php#L80-L83)



#### Returns

[yii\db\ActiveQueryInterface](https://www.yiiframework.com/doc/api/2.0/yii-db-activequeryinterface) – The relational query object.



### `getStructure()` {#method-getstructure}





Returns the structure element’s structure.




[View source](https://github.com/craftcms/cms/blob/3.9.14/src/records/StructureElement.php#L70-L73)



#### Returns

[yii\db\ActiveQueryInterface](https://www.yiiframework.com/doc/api/2.0/yii-db-activequeryinterface) – The relational query object.



### `rules()` {#method-rules}





Returns the validation rules for attributes.



Validation rules are used by [validate()](https://www.yiiframework.com/doc/api/2.0/yii-base-model#validate()-detail) to check if attribute values are valid.
Child classes may override this method to declare different validation rules.

Each rule is an array with the following structure:

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

where

  • attribute list: required, specifies the attributes array to be validated, for single attribute you can pass a string;
  • validator type: required, specifies the validator to be used. It can be a built-in validator name, a method name of the model class, an anonymous function, or a validator class name.
  • on: optional, specifies the scenarios array in which the validation rule can be applied. If this option is not set, the rule will apply to all scenarios.
  • additional name-value pairs can be specified to initialize the corresponding validator properties. Please refer to individual validator class API for possible properties.

A validator can be either an object of a class extending \craft\records\Validator, or a model class method (called inline validator) that has the following signature:

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

In the above $attribute refers to the attribute currently being validated while $params contains an array of validator configuration options such as max in case of string validator. The value of the attribute currently being validated can be accessed as $this->$attribute. Note the $ before attribute; this is taking the value of the variable $attribute and using it as the name of the property to access.

Yii also provides a set of built-in validators. Each one has an alias name which can be used when specifying a validation rule.

Below are some examples:

php
[
    // 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'],
];

Note, in order to inherit rules defined in the parent class, a child class needs to merge the parent rules with child rules using functions such as array_merge().

View source

Returns ​

array – Validation rules

tableName() ​

Declares the name of the database table associated with this AR class.

By default this method returns the class name as the table name by calling yii\helpers\Inflector::camel2id() with prefix yii\db\Connection::$tablePrefix. For example if yii\db\Connection::$tablePrefix is tbl_, Customer becomes tbl_customer, and OrderItem becomes tbl_order_item. You may override this method if the table is not named after this convention.

View source

Returns ​

string – The table name

transactions() ​

Declares which DB operations should be performed within a transaction in different scenarios.

The supported DB operations are: OP_INSERT, OP_UPDATE and OP_DELETE, which correspond to the insert(), update() and delete() methods, respectively. By default, these methods are NOT enclosed in a DB transaction.

In some scenarios, to ensure data consistency, you may want to enclose some or all of them in transactions. You can do so by overriding this method and returning the operations that need to be transactional. For example,

php
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,

];

The above declaration specifies that in the "admin" scenario, the insert operation (insert()) should be done in a transaction; and in the "api" scenario, all the operations should be done in a transaction.

View source

Returns ​

array – The declarations of transactional operations. The array keys are scenarios names, and the array values are the corresponding transaction operations.

Protected Methods ​

MethodDescription
createRelationQuery()Creates a query instance for has-one or has-many relation.
deleteInternal()Deletes an ActiveRecord without considering transaction.
extractFieldsFor()Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id".
extractRootFields()Extracts the root field names from nested fields.
insertInternal()Inserts an ActiveRecord into DB without considering transaction.
prepareForDb()Sets the dateCreated, dateUpdated, and uid attributes on the record.
refreshInternal()Repopulates this active record with the latest data from a newly fetched instance.
resolveFields()Determines which fields can be returned by toArray().
updateInternal()

Constants ​

ConstantDescription
OP_ALLAll three operations: insert, update, delete.
OP_DELETEThe delete operation. This is mainly used when overriding transactions() to specify which operations are transactional.
OP_INSERTThe insert operation. This is mainly used when overriding transactions() to specify which operations are transactional.
OP_UPDATEThe update operation. This is mainly used when overriding transactions() to specify which operations are transactional.
SCENARIO_DEFAULTThe name of the default scenario.