Question

I'm trying to find a Question that have custom field userAnswered equal 0.

I cannot figure out wheres the problem.


Code:

    $criteria=new CDbCriteria;
    $criteria->with='answers';
    $criteria->select='*, count(answers.id) as userAnswered';
    $criteria->condition='userAnswered=:userAnswered';
    $criteria->params=array(':userAnswered'=>0);
    $model=Question::model()->find($criteria);

Question Model:

class Question extends CActiveRecord
{
    public $userAnswered;

...

public function relations()
{
    return array(
        'answers' => array(self::HAS_MANY, 'Answer', 'answer_id'),
    );
} 

Yii Error Returned:

SQL: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'userAnswered' in 'where clause'.
Was it helpful?

Solution

I found the answer here: condition in criteria in yii framework php

Code:

$criteria=new CDbCriteria;
$criteria->with='answers';
$criteria->select='*, count(answers.id) as userAnswered';
$criteria->having='userAnswered=0';
$model=Question::model()->find($criteria);

OTHER TIPS

Question has a HAS_MANY connection with Option. When you perform a select from Question with Option you are actually running 2 selects, 1 to bring the Question details, the second to bring over the options.

You are doing a SELECT FROM Question WHERE criteria_conditions + a SELECT FROM Option WHERE ...

So you cannot put a condition in the criteria on anything related from Option because it will fail on the first select.

You have 2 options now:
1) to use $criteria->together = true; Read more here http://www.yiiframework.com/wiki/280/1-n-relations-sometimes-require-cdbcriteria-together/
2) To create the criteria condition something like $items = Something::model()->with(array('relationname'=>array('condition'=>'')))->find...

I am not sure if the second one will work but it should, I already use 'order'=> to order the records, I believe 'condition' should also work.

The 2 options might produce different results so make sure you use the one that you need.

You can't use aliased columns in a WHERE clause.

You have to use :

$criteria->condition = 'count(userOptions.id) =:userAnswered';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top