【问题标题】:Yii left join by CDbCriteriaYii 离开加入 CDbCriteria
【发布时间】:2012-12-13 15:33:29
【问题描述】:

有两张桌子:

内容

 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) 只返回内容数据,没有照片数据。

就像this 我试过的答案:

print_r($content->photos);

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

我做错了什么?

【问题讨论】:

  • 在内容控制器中添加了功能?它应该在内容模型中
  • 啊,我为此浪费了半天时间。谢谢!请将其添加为答案,我将其标记为解决方案。

标签: php join yii left-join


【解决方案1】:

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

class Content extends CActiveRecord {

    // ... other functions ...

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

}

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

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    • 1970-01-01
    相关资源
    最近更新 更多