繁体   English   中英

Yii离开CDbCriteria加入

[英]Yii left join by CDbCriteria

有两张桌子:

内容

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

相片

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

试图从左边加入来自第三个控制器的照片获取内容。

我的代码:

$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);

在ContentController中添加了功能:

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

print_r($content)仅返回内容数据,没有照片数据。

就像在这个答案中我试过:

print_r($content->photos);

但得到的Property "Content.photos" is not defined.

我究竟做错了什么?

您已将关系功能添加到错误的位置。 它应该添加到Content模型,而不是ContentController

class Content extends CActiveRecord {

    // ... other functions ...

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

}

如果您使用Gii生成了模型,那么关系函数应该已经存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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