Abudayah
Abudayah

Reputation: 3875

Yii relations: get data form another table

I have Movie table & TblMovieVideos table and I have relations with this tables, so I need to get "youtube_id" form TblMovieVideos where "trailer=1"

I think I need to get result by this code but it's wrong Error: $model->tblMovieVideos[$model->id]->trailer = 1 ->youtube_id ??????

(data base images was attached)

Movie Model:

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(
            'tblCinemaMovies' => array(self::HAS_MANY, 'TblCinemaMovies', 'movie_id'),
            'tblDays' => array(self::HAS_MANY, 'TblDay', 'movie_id'),
            'tblGenres' => array(self::HAS_MANY, 'TblGenre', 'movie_id'),
            'tblMoviePhotos' => array(self::HAS_MANY, 'TblMoviePhoto', 'movie_id'),
            'tblMovieVideos' => array(self::HAS_MANY, 'TblMovieVideo', 'movie_id'),
            'tblShowtimes' => array(self::HAS_MANY, 'TblShowtime', 'movie_id'),
        );
    }

TblMoviesVideos Model:

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(
        'movie' => array(self::BELONGS_TO, 'TblMovie', 'movie_id'),
        'tblSpotlights' => array(self::HAS_MANY, 'TblSpotlight', 'video_id'),
    );
}

enter image description here

enter image description here

Indexes: enter image description here

Upvotes: 0

Views: 5903

Answers (2)

Kshitiz
Kshitiz

Reputation: 2743

There is another way of getting the related data

Step 1: Use the yii gii tool to generate the model with checked Build relation check box.

This will generate the relation() code automatically.

Step 2: Now to get the relate data do this

foreach($data as $d){
 $d->relationOne->name;
}

relationOne is from the relation method in your model.php file

I know this is not a great way to answer, pardon me for this. Also gii is a great too to build relation without any difficulty.

I will improve this answer. Later

Upvotes: 0

Puigcerber
Puigcerber

Reputation: 10124

You can get all the movies that have trailer with this:

$movies=Movie::model()->with(array('tblMovieVideos'=>array('condition'=>'trailer = 1')))->findAll();

But as what you want is the youtube_id, try this:

$id = 1;//Id of the movie for which you are trying to find the video
$videos = TblMoviesVideos::model()->findAllByPk($id, 'trailer = 1');
foreach ($videos as $video)
{
    echo $video->youtube_id;
}

Cheers.

Upvotes: 2

Related Questions