2011-01-27 84 views
2

我有一个问题,我甚至无法正确命名。这是情况。在方法中访问父对象

我使用PHP框架(kohana3,但它不是重要的我认为)编写一个简单的cms条目和上传。的关系是:

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

与他们上传显示所有条目,我使用这个代码在视图文件:

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

现在我想创建输入模型的方法称为find_first_upload()这将返回第一个上传的元素。这里是它未来的使用量:

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

和最重要的事情是,我不想传递任何变量find_first_upload()方法例如像$entry对象或当前循环条目ID。 我想实现的目标是能够获得find_first_upload方法中的当前循环条目对象 - 它允许我将foreach放入其中。

你有什么想法,我怎么可以编码?

如果您有任何问题,请随时在此处询问。

谢谢, 迈克

回答

1

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

是啊!这就是我一直在寻找:)非常感谢!但我不明白一件事。我可以在模型中使用`return $ upload-> file`显示`file`属性,但是如果我在`**'视图中编写`return $ upload`并使用`echo $ entry-> find_first_upload() - > file` ** ,我得到`未定义的属性:Database_MySQL_Result :: $ file`错误。这怎么可能?对于我来说能够从视图 – mbajur 2011-01-27 20:39:09

1

对不起重振这个老话题,但我是谷歌搜索的东西,无意中发现了这一点。如果有人有类似的问题,忽略接受的答案,这是正确的方法:

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