获取Yii中相册的照片(关联情况)


fetch photos of an album in Yii (relation case)

我有两个表,一个相册和一张照片。照片表中有一个FK (album_id),它引用了相册表中的id。

现在我想在CListview中显示照片,但我不知道怎么做。(

当我看到它是使用dataProvider,我不知道如何结合关系与它。

你能帮我吗?谢谢各位大师。

很简单

$dataProvider=new CActiveDataProvider('Photo', array(
    'criteria'=>array(
        'condition'=>'album_id=:album_id',
        'params'=>['album_id'=>$album_id]
    )
));

然后在视图中使用这个dataProvider:

$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_photo'
));

首先您应该在您的模型中创建关系。在Album.php中添加如下内容:

public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'photos'=>array(self::HAS_MANY, 'Photo',array('album_id'=>'id')),
    );
}
类似于Photo.php:
public function relations()
{
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
    return array(
        'album'=>array(self::BELONGS_TO, 'Album',array('id'=>'album_id')),
    );
}

现在你可以在你的代码中使用它:

$dataProvider=new CActiveDataProvider('Photo', array(
    'criteria'=>array(
        'condition'=>'album_id='.$yourAlbumId,
    )
));
$this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
...
));

如果您需要在CListview中引用Album(假设您在Album模型中有一个名为"title"的字段),则可以在项目模板中将其引用为$data->album->title