如何在Yii2 ActiveRecord中获取属性标签

Piy*_*ush 9 activerecord yii2

如何在Yii2中获取属性标签?

我发现这个功能getAttributeLabel() 在这里的Yii2文档,我在控制器中使用它.但这是一个错误:

Call to undefined function app\controllers\getAttributeLabel()

Pra*_*lad 16

$task = new Task();

//to get single attribute label
$label = $task->getAttributeLabel('task_title');

//to get all attribute label
$labels = $task->attributeLabels();
Run Code Online (Sandbox Code Playgroud)


Blo*_*und 9

试试这个

$model          =   new ModelName();
print_r($model->attributeLabels());
Run Code Online (Sandbox Code Playgroud)

如果使用上面的代码,则可以获得包含模型的所有属性标签的数组


rob*_*006 6

由于 Yii 2.0.13ActiveRecord实现了StaticInstanceInterface,所以你可以instance()用来获取模型的静态实例。使用它应该比手动创建模型实例以使用其非静态方法更干净、更高效。

$singleLabel = MyModel::instance()->getAttributeLabel('my_attribute');

$allLabels = MyModel::instance()->attributeLabels();
Run Code Online (Sandbox Code Playgroud)