Narek
Narek

Reputation: 3823

Yii left join by CDbCriteria

Have two tables:

Content

 id |  text
------------
 1  | text1
 2  | text2
 3  | text3
 4  | text4

Photos

 id |  content_id |  src
-----------------------------
 1  |      1      |  img1.png
 2  |      1      |  img2.png
 3  |      2      |  img3.png
 4  |      3      |  img1.png

Trying to get content with left joined photos from third controller.

My code:

$oDBC = new CDbCriteria();
$oDBC->select = 't.*,p.*'; 
$oDBC->join = 'LEFT JOIN photos p ON t.id = p.content_id'; 
$oDBC->condition = 't.step_id = "'.$model->id.'"';

$content = Content::model()->find($oDBC);

In ContentController added function:

public function relations()
{
    return array('photos' => array(self::HAS_MANY, 'Photos', 'content_id');
}

But print_r($content) returns only content data, without photos data.

Like in this answer I tried:

print_r($content->photos);

but got Property "Content.photos" is not defined.

What am I doing wrong?

Upvotes: 1

Views: 11919

Answers (1)

bool.dev
bool.dev

Reputation: 17478

You have added the relations function in the wrong place. It should be added to the Content model, and not ContentController:

class Content extends CActiveRecord {

    // ... other functions ...

    public function relations() {
        return array('photos' => array(self::HAS_MANY, 'Photos', 'content_id');
    }

}

If you have generated your model with Gii, then the relations function should already be there.

Upvotes: 4

Related Questions