Changes
Title
unchanged
Accessing data in a join table with the related models
Category
unchanged
How-tos
Yii version
unchanged
Tags
unchanged
relations, active record, many_many, join table
Content
changed
[...]
```php
class Viewer extends CActiveRecord {
...
public function relations() {
return array(
'movies' => 'movies' -> array(self::MANY_MANY, 'Movie',
'viewer_watched_movie(
movie
wer_id, movie_id)'),
...
```[...]
echo $viewer . ' watched ' . $movie->title;
```
[This will perform poorly because it lazily loads `Movie`s one ast a time in the loop. I can pep it up thus: `Viewer::model()->with('movies')->findByPk($id)`]
### The problem[...]
'watched' => array(self::HAS_MANY, 'ViewerWatchedMovie', 'viewer_id'),
'movies' => array(self::HAS_MANY, 'Movie', 'movie_id',
'through' => 'moviesJoinwatched'),
...
```[...]
To make it eager: `Viewer::model()->with('watched', 'movies')->findByPk($id)`.
I have it on [good authority](http://www.yiiframework.com/forum/index.php?/topic/8581-selecting-join-table-with-mant-to-many/page__st__40__p__123710__hl__creocoder#entry123710 "forum link") that the coherence of indexes of the two arrays `$viewer->moviesJoinwatched` and `$viewer->movies` is assured. But this fact (feature?) is not documented so it makes me nervous. That's why I prefer a variation.
Add a relation to the `ViewerWatchedMovie` model:
```php
class ViewerWatchedMovie extends CActiveRecord {[...]