在Yii中获取相册的照片(关系案例)

I have two tables , one album and one photo. the photo table has a FK (album_id) which refer to id in album table.

now I want to show photos in CListview but I don't know how. :(

As I see it is uses dataProvider and I don't know how to combine relation with it.

would you help me? Thank you masters.

It's simple

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

Then in view use this dataProvider:

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

First you should create the relation in you models. In Album.php add sth like this:

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')),
    );
}

Similar in 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')),
    );
}

Now you can use it in your code:

$dataProvider=new CActiveDataProvider('Photo', array(
    'criteria'=>array(
        'condition'=>'album_id='.$yourAlbumId,
    )
));

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

If you need to refer to the Album in the CListview (let's say you have a field called "title" in the Album model), you can refer to it as $data->album->title in your items template.