简体   繁体   中英

STAT Relation in Related Model in Yii

I am not sure on the correct logic to use in the following situation. This situation will come up several times in my app and I would assume, it may be experienced by others as well.

In Yii I have a loadModel function that is returning a CActiveRecord.

The function is as follows:

$model=Product::model()->with('performance','subcategory','sponsor')->findByPk($id);

As you can see, I am eagerly calling 3 relationships. One of those relationships - performance - is a HAS_MANY relationship and relates to user reviews of the product.

So for product x, there may be 100 reviews all with different dates and scores.

What I am attempting to do is:

  1. Pull all performance data (so all 100 reviews)
  2. Pull the most recent performance data score (as long as it was submitted within the last 120 days)

The confusion in logic is this. Should I create a function in my model class that goes through $model->performance to get the most recent information (#2).

Should I create an entirely separate relation just for this refined piece of data.

This most recent review data will be needed for each product in the CListView and the ListView needs to be sortable by this data. So, it seems as though it needs to be directly attached to the product active record that is being passed in to the view.

From both a performance standpoint and logic standpoint, how should I handle this?

As an aside, here is the current code I was trying to use that is not functioning:

public function scopes()
{
    return array(
        'recentPerf'=>array(
            'condition'=>'perf_date > ' . strtotime('-120 days', strtotime(new CDbExpression('NOW()'))),
            'order'=>'perf_date DESC',
            'limit'=>1,
        )
    );
}

Thank you in advance for any suggestions!

Uday's answer got the scope working - now how is the correct way to use the scope? Should I pass this amount in with the current model?

ie can I attach this to the:

$model=Product::model()->with('performance','subcategory','sponsor')->findByPk($id);

? How I tested it to make sure it worked was:

$maxPerformance = ProdPerformance::model()->recentPerf()->find();

and am then passing that variable to the view. This seems like a very 'unclean' way of handling this situation. Should it instead be passed with the original $model variable?

I am not sure but possibly following line has a catch

'condition'=>'perf_date > ' . strtotime('-120 days', strtotime(new CDbExpression('NOW()'))),

condition is the data that will be sent to mysql so the date string should be in MySQL format not in PHP, try this

'condition'=>'perf_date > CURRENT_DATE - INTERVAL 120 DAYS',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM