简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM