Yii2 ActiveRecord 如何只从模型中获取填充的属性?
Yii2 ActiveRecord how to get only populated attributes from model?
使用 ActiveRecord 检索模型时,可以 select 几列。例如:
Product::find()->select('product_id,name')->all();
数据库中的列比product_id
和name
多,但是这个例子returns一个数组填充了所有模型,只有product_id
和name
属性填充。这当然是意料之中的,因为我已经将它们传递给 select()
.
现在,当遍历找到的模型并调用 $model->getAttributes()
时,returns 一个 所有 模型属性及其值的数组(null
对于未 selected 属性),包括所有未在查询中 selected 但在模型的 attributes()
函数中的列。
有没有一种方法可以调用类似于 getAttributes()
的函数,但只返回查询中 selected 的填充属性:product_id
和 name
?
我知道可以将排除项传递给 getAttributes()
,但我更愿意根据我在 ActiveRecord 查询中 select 编辑的值返回填充的属性。
在你的情况下,你应该能够使用 fields()
方法:
$attributes = $model->getAttributes($model->fields());
请注意,如果您在查找后更改模型,fields()
不保证此行为 - 取消设置 (unset($model->product_id)
) 或设置 ($model->some_field = 'some value'
) 属性将影响 [=11= 的结果].
使用 ActiveRecord 检索模型时,可以 select 几列。例如:
Product::find()->select('product_id,name')->all();
数据库中的列比product_id
和name
多,但是这个例子returns一个数组填充了所有模型,只有product_id
和name
属性填充。这当然是意料之中的,因为我已经将它们传递给 select()
.
现在,当遍历找到的模型并调用 $model->getAttributes()
时,returns 一个 所有 模型属性及其值的数组(null
对于未 selected 属性),包括所有未在查询中 selected 但在模型的 attributes()
函数中的列。
有没有一种方法可以调用类似于 getAttributes()
的函数,但只返回查询中 selected 的填充属性:product_id
和 name
?
我知道可以将排除项传递给 getAttributes()
,但我更愿意根据我在 ActiveRecord 查询中 select 编辑的值返回填充的属性。
在你的情况下,你应该能够使用 fields()
方法:
$attributes = $model->getAttributes($model->fields());
请注意,如果您在查找后更改模型,fields()
不保证此行为 - 取消设置 (unset($model->product_id)
) 或设置 ($model->some_field = 'some value'
) 属性将影响 [=11= 的结果].