Jelmer Keij
Jelmer Keij

Reputation: 1606

Yii2 ActiveRecord how to get only populated attributes from model?

When using an ActiveRecord to retrieve models it's possible to select a few columns. For example:

Product::find()->select('product_id,name')->all();

There are more columns than product_id and name in the database, but this example returns an array filled with all models, having only the product_id and name attributes filled. This is expected of course because I've passed them into select().

Now when looping through the found models and calling $model->getAttributes() it returns an array of all model attributes and their values (null for the not-selected attributes), including all columns that were not selected in the query but are in the model's attributes() function.

Is there a way to call a function similar to getAttributes() but returning only the populated attributes that were selected in the query: product_id and name?

I know it's possible to pass in exclusions to getAttributes() but I'd rather have the populated attributes returned based on the values I've selected in the ActiveRecord query.

Upvotes: 0

Views: 1704

Answers (1)

rob006
rob006

Reputation: 22174

In your case you should be able to use fields() method:

$attributes = $model->getAttributes($model->fields());

Note that fields() does not guarantee this behavior if you change model after find - unsetting (unset($model->product_id)) or setting ($model->some_field = 'some value') attributes will affect result of fields().

Upvotes: 3

Related Questions