When retrieving a record in a service and returning a model the static methods: populateModel and populateModels on BaseModel are useful.

When eager loading a related model in the record query, for example:

$variantRecord = Market_VariantRecord::model()->with('product')->findById($id);

This will load the related Record's product into the $variantRecord accessible with $variantRecord->product

when casting this variant record into a Model, using VariantModel::populateModel, will the product also being retrieved be cast into the model->product (AttributeType::Mixed) of the variant?

Or should we manually be manually assigning the ->product attribute as casting it to a model with populate model like this?

$variant = Market_VariantRecord::model()->with('product')->findById($id);
$variantModel = Market_VariantModel::populateModel($variant);
$variantModel->product = Market_ProductModel::populateModel($variant->product);
return $variantModel;

This seems clunky and am looking for suggestions on improving the population of models from records with eager loading of relations.

This is one area


Would like to know if this is the best solution? Upvote if you think it is.

The solution is make your own custom populateModel method to catch the eager loaded attributes

 * @param array|Market_VariantRecord $values
 * @return $this
public static function populateModel($values)
    $model = parent::populateModel($values);
    if (is_object($values) && $values instanceof Market_ProductRecord) {
        $model->product = $values->product;

    return $model;

I suppose the Craft core BaseModel could check if the value of type BaseRecord and do the same?

  • I think you're spot on both with the original workaround as well as the solution in your answer. Craft currently doesn't have support for this in populateModel(s), although we'd have to make a more generic solution that would work for any record (not just Market_ProductRecord) in your answer.
    – Brad Bell
    Feb 10 '15 at 16:42
  • thats for the comment brad, I am moving to the answer solution to all my models that have eager loaded relations. Feb 11 '15 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.