当使用ActiveRecord来检索模型时,可以选择一些列。例如,当使用ActiveRecord检索模型时,可以选择一些列。
Product::find()->select('product_id,name')->all();
有更多的列比 product_id
和 name
在数据库中,但这个例子返回的是一个充满所有模型的数组,其中只有 product_id
和 name
属性填充。这当然是意料之中的,因为我已经把它们传到了 select()
.
现在,当循环浏览找到的模型并调用 $model->getAttributes()
它返回一个由 都 模型属性及其值(null
为未选择的属性),包括所有在查询中未被选择但在模型的 attributes()
函数。
有没有办法调用一个类似于 getAttributes()
但只返回查询中选择的填充属性。product_id
和 name
?
我知道有可能将排除物传递到 getAttributes()
但我更希望根据我在ActiveRecord查询中选择的值返回填充的属性。
在你的情况下,你应该可以使用 fields()
方法。
$attributes = $model->getAttributes($model->fields());
注意: fields()
如果你在find之后改变了模型,并不能保证这种行为 - 解除设置 (unset($model->product_id)
)或设置($model->some_field = 'some value'
)的属性会影响 fields()
.