Difference between #6 and #8 of
Accessing data in a join table with the related models

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(moviewer_id, movie_id)'),
...
```
[...]
echo $viewer . ' watched ' . $movie->title;
```
[This will perform poorly because it lazily loads `Movie`s one a
st 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 {
[...]
16 1
30 followers
Viewed: 147 713 times
Version: 1.1
Category: How-tos
Written by: fsb
Last updated by: krowe
Created on: Dec 5, 2011
Last updated: 12 years ago
Update Article

Revisions

View all history