我还是Yii的新手,但是我尝试使用relations()来连接两个表,并从每一行的两个表中获取所有数据。
tables:
TABLE Artist KEYS(artist_Id, firstName, lastName)
TABLE Album KEYS(album_Id, title, artist_Id, genre)
// Album
public function relations()
{
return array(
'artist' => array(self::BELONGS_TO, 'Artist', 'artist_Id'),
'track' => array(self::HAS_MANY, 'Track', 'track_Id')
);
}
// Artist
public function relations()
{
return array(
'album' => array(self::HAS_MANY, 'Album', 'album_id')
);
}
// logic for getting information
$dataProvider=new CActiveDataProvider('Album');
foreach($dataProvider->getData() as $key){
echo '<br>' . $key->artist_Id; // does work
echo '<br>' . $key->firstName; // doesn't work
}
使用此代码,我可以获得并显示相册的正确artist_Id。但是,我想使用artist_Id显示艺术家firstName和lastName。
答案 0 :(得分:0)
我需要更改我的$dataProvider
变量以及我在视图中尝试访问的方式index.php
$dataProvider = new CActiveDataProvider('Album');
-to -
$dataProvider = new CActiveDataProvider('Album', array('criteria' => array('with' => array('artist'))));
并将视图index.php更改为两者之一:
'name' => 'artist.lastName',
或
'value' => '$data->artist->firstName'