X
X
x2bool2012-05-28 10:49:25
Yii
x2bool, 2012-05-28 10:49:25

One to many in ActiveRecord and condition in CDbCriteria?

Two models:

class Model1 extends CActiveRecord {
    function relations() {
        return array(
            'Model2' => array(self::HAS_MANY, 'Model2', 'model1_id')
        )
    }
  }

  class Model2 extends CActiveRecord {
    public $foo;
    function relations() {
        return array(
            'Model1' => array(self::BELONGS_TO, 'Model1', 'model1_id')
        )
    }
  }

Model search by condition:
$criteria->with = array('Model2');
  $criteria->addCondition("Model2.foo = 'bar'");
  Model1::model()->findAll($criteria);

As a result:
Unknown column 'Model2.foo' in 'where clause'.<br/>

Is that how it should happen? Does HAS_MANY allow code like this? If not, how to find all Model1s that have Model2s with foo = 'bar'?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Prokhorov, 2012-05-28
@x2bool

It would be better to see the full SQL query. Now I see 2 possible reasons:
- lazy loading occurs, $criteria->together = true is missing;
- the foo field is not in the Model2 table

R
rakot, 2012-05-28
@rakot

I'm confused by public $foo; in the Model2 definition, why is it there?

S
Sergey, 2012-05-28
Protko @Fesor

$criteria->addCondition("Model2.foo = 'bar'");
You will have a Model2 table with another alisas. The solution to this problem can be either to set the together criterion to true, or simply to see which alias is assigned to the table.
In Yii2, it seems like they added a bun in order for Yii itself to substitute the necessary aliases in the sulovia.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question