Not signed in (Sign In)
Welcome Guest!
Want to take part in these discussions? If you have an account, sign in now.
If you don't have an account, apply for one now.
    • CommentAuthorgamma
    • CommentTimeDec 2nd 2007
     
    Hi,

    I use the habtm relation to connect the model Movie and the model Actor over a 'actors_movies' table.

    <code>
    class Movie extends ActiveRecord
    {
    var $has_and_belongs_to_many = 'actors';

    class Actor extends ActiveRecord
    {
    var $habtm = 'movies';
    }
    </code>

    How do i access all actors who belongs to a movie (e.g. Matrix) and how do i create a new actor who belongs to a movie in the movie controller.
    • CommentAuthorbhembree
    • CommentTimeDec 3rd 2007
     
    I put a tutorial for implementing a simple many-to-many relationship up on the wiki. Take a look at it and see if it helps.
    • CommentAuthorgamma
    • CommentTimeDec 4th 2007
     
    Thanks, it realy helps.
    If i load a movie like $this->Movie->find($id), how can i access the related Actors. Do i have to load them manualy in the Object?
    • CommentAuthorbhembree
    • CommentTimeDec 4th 2007
     
    Yes. You can use a statement like:

    $this->Movie->actor->load();

    If you put the above statement in your show() method for your movie_controller.php, you can then add the following code to your show.tpl file (or move it to a helper method if you like) :

    <?php
    foreach (array_keys ($Movie->actors) as $k {
    $actor_name = $Movie->actors[$k]->gat('name');
    }

    This will put the name for the actor in the variable $actor_name and you can then display it using whatever method you like.

    There may be a better way but this is what has worked for me so far.
    • CommentAuthorKaste
    • CommentTimeDec 4th 2007 edited
     

    How do i access all actors who belongs to a movie (e.g. Matrix)

    we start with on actors:

    $this->Actor->find('all');
    

    include the movies

    $this->Actor->find('all',array('include'=>'movies'));
    

    restrict the set using conditions

    $this->Actor->find('all',
              array('_movies.name'=>'Matrix'),
              array('include'=>'movies')
    );
    
    • CommentAuthorsuthern
    • CommentTimeDec 10th 2007
     

    FYI: There should be a closing single quote on the 'include the movies' section.

Add your comments
    Username Password
  • Format comments as