Note that there are some explanatory texts on larger screens.

plurals
  1. POSTAT Relation in Related Model in Yii
    text
    copied!<p>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.</p> <p>In Yii I have a loadModel function that is returning a CActiveRecord.</p> <p>The function is as follows:</p> <pre><code>$model=Product::model()-&gt;with('performance','subcategory','sponsor')-&gt;findByPk($id); </code></pre> <p>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.</p> <p>So for product x, there may be 100 reviews all with different dates and scores.</p> <p>What I am attempting to do is:</p> <ol> <li>Pull all performance data (so all 100 reviews)</li> <li>Pull the most recent performance data score (as long as it was submitted within the last 120 days)</li> </ol> <p>The confusion in logic is this. Should I create a function in my model class that goes through <code>$model-&gt;performance</code> to get the most recent information (#2). </p> <p>Should I create an entirely separate relation just for this refined piece of data.</p> <p>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.</p> <p>From both a performance standpoint and logic standpoint, how should I handle this?</p> <p>As an aside, here is the current code I was trying to use that is not functioning:</p> <pre><code>public function scopes() { return array( 'recentPerf'=&gt;array( 'condition'=&gt;'perf_date &gt; ' . strtotime('-120 days', strtotime(new CDbExpression('NOW()'))), 'order'=&gt;'perf_date DESC', 'limit'=&gt;1, ) ); } </code></pre> <p>Thank you in advance for any suggestions!</p> <p>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?</p> <p>i.e. can I attach this to the:</p> <pre><code>$model=Product::model()-&gt;with('performance','subcategory','sponsor')-&gt;findByPk($id); </code></pre> <p>? How I tested it to make sure it worked was:</p> <pre><code>$maxPerformance = ProdPerformance::model()-&gt;recentPerf()-&gt;find(); </code></pre> <p>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 <code>$model</code> variable?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload