Note that there are some explanatory texts on larger screens.

plurals
  1. POCGridView filtering with aggregate (grouping) functions - eg MAX()
    text
    copied!<p>I have a CGridView that uses a <code>MAX()</code> mysql column to provide data for one of the columns. I have that working with sorting, but I can't figure out filtering. I assumed that I could just use <code>CDbCriteria::compare()</code> call to set it, but it's not working. Ideas?</p> <p>My search function:</p> <pre><code> $criteria = new CDbCriteria; $criteria-&gt;condition = 't.is_deleted = 0 and is_admin = 0'; // get last note date $criteria-&gt;select = array('t.*', 'MAX(n.visit_date) AS last_note'); $criteria-&gt;join = 'LEFT JOIN notes n ON t.id = n.distributor_id'; $criteria-&gt;group = 't.id'; $criteria-&gt;order = 't.status'; $criteria-&gt;compare('t.type', $this-&gt;type); $criteria-&gt;compare('t.name', $this-&gt;name, true); $criteria-&gt;compare('t.city', $this-&gt;city, true); $criteria-&gt;compare('t.state', $this-&gt;state); $criteria-&gt;compare('last_note', $this-&gt;last_note); return new CActiveDataProvider('Distributor', array( 'criteria' =&gt; $criteria, 'pagination' =&gt; array( 'pageSize' =&gt; 20 ), 'sort' =&gt; array( 'defaultOrder' =&gt; 'name', 'attributes' =&gt; array( 'last_note' =&gt; array( 'asc' =&gt; 'last_note', 'desc' =&gt; 'last_note DESC' ), ) ), )); </code></pre> <p>In my view, I just have the name and value values set.</p> <p>The error I get is <code>CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_note' in 'where clause'</code></p> <p>Edit: The only way I found to do this is (because you can't have aggregate functions in where clauses) is to check the <code>$_GET</code> array for the last_note value, and add a having clause. Note, this isn't parameterized or anything yet, I just wanted to rough it out to see if it would work:</p> <pre><code>if(isset($_GET['Distributor']['last_note']) &amp;&amp; $_GET['Distributor']['last_note'] != '') { $criteria-&gt;having = 'MAX(n.visit_date)=\'' . $this-&gt;last_note . "'"; } </code></pre> <p>I hate using the request variables in the model like this, but there isn't much else I could do.</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