Access parent object in method

351 views Asked by At

I have a problem i can't even name properly. Here is the situation.

I'm using php framework (kohana3 but it's not important i think) to write a simple cms with entries and uploads. The relations are:

Entries -> has_many -> Uploads
Uploads -> belongs_to -> Entries

To display all entries with their uploads, i'm using this code in view file:

foreach( $entries as $entry ) 
{
     foreach( $entry->upload->find_all() as $uploads ) 
     {
          foreach( $uploads->find_all() as $upload )
          {
               echo $upload->file;
          }
     }
}

Now i want to create a method in Entry model called find_first_upload() which will return first uploaded element. Here is the future usage of it:

foreach( $entries as $entry ) 
{
     echo $entry->find_first_upload()->file;
}

and the important thing is that i don't want to pass any variables to find_first_upload() method like for example $entry object or currently looped entry id. What i want to achieve is to be able to get currently looped entry object inside find_first_upload method - it'll allow me to make a foreach's inside of it.

Have you any ideas how can i code that?

If you have any questions, feel free to ask them here.

Thanks, Mike

2

There are 2 answers

7
AmirModiri On BEST ANSWER

public function find_first_upload() {
    $result = 0;
     foreach( $this->upload->find_all() as $uploads ) 
         {
              foreach( $uploads->find_all() as $upload )
              {
                if(empty($result))
                   $result = $upload;
              }
         }
        return $result;
}
0
Daniel On

Sorry for reviving this old topic, but I was googling something and stumbled on this. In case anyone has a similar issue, ignore the accepted answer, this is the correct way:

public function find_first_upload()
{
    return $this->uploads->find();
}