The simplest way of converting a model into an array is to use the yii\base\Model::$attributes property. For example,
$post = \app\models\Post::findOne(100);
$array = $post->attributes;
By default, the yii\base\Model::$attributes property will return the values of all attributes declared in yii\base\Model::attributes().
A more flexible and powerful way of converting a model into an array is to use the yii\base\Model::toArray() method. Its default behavior is the same as that of yii\base\Model::$attributes. However, it allows you to choose which data items, called fields, to be put in the resulting array and how they should be formatted. In fact, it is the default way of exporting models in RESTful Web service development, as described in the Response Formatting.
// using toArray() to export model
$array = $model->toArray([]);
If you want to omit some attributes from exporting to array, you may do so by overriding field()
method of the model.
// filter out some fields, best used when you want to inherit the parent implementation
// and exclude some sensitive fields.
public function fields()
{
$fields = parent::fields();
// remove fields that contain sensitive information
unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);
return $fields;
}
In the above example, we choose to filter out auth_key
, password_hash
and password_reset_token
. These fields won’t be exported to the resulting array.