Yii - 在模型二级中定义关系

时间:2014-12-01 08:56:22

标签: yii relationship

我想知道模型中是否可以通过两个表来定义关系。

我想从图片模型开始,并获得相对的地方模型。

我有图片模型:

id | event_id

我的活动模型有:

id | place_id

我有Place模型:

id

我知道我可以这样做:$model->event->place;

但我只是想知道它是否可能。

我的目标是创建一个recursiveEncode方法,然后传递" place"为了获得良好的格式化JSON。

谢谢!

2 个答案:

答案 0 :(得分:2)

这样的事情:

class Picture extends CActiveRecord {
...
    public function relations () {
        return array(
            'event' => array( self::BELONGS_TO, 'Event', 'event_id' ),
            'place' => array( self::BELONGS_TO, 'Place', array('place_id'=>'id'), 'through' => 'event' ),
        );
    }
...
}

答案 1 :(得分:1)

使用Yiiwith关联,through尽可能简单。正如Yii的官方文件:

<强>到

  

获取相关数据时将用作桥梁的模型关系的名称。只能为HAS_ONE和HAS_MANY设置。

<强>与

  

string | array,应与此对象一起加载的子相关对象的列表。请注意,这只是延迟加载,而不是急切加载。

示例

    'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
    'comments'=>array(self::HAS_MANY, 'Comment', 'post_id', 'with'=>'author')

然后,您可以使用.访问相关对象。例如parent.child

http://www.yiiframework.com/doc/api/1.1/CActiveRecord#relations-detail