2013-02-11 146 views
0

我試圖打印包含記錄的總列表,對於此列表,有些可能與用戶連接。活動項目來自同一班級的另一個集合(活動集合)。我會對整個列表進行foreach,並且需要檢查每個記錄是否存在於活動集合中。 有沒有這個功能?Kohana 3.2 ORM檢查集合中是否存在記錄

現在我把活動項放在一個數組中,記錄ID作爲數組鍵以檢查,並且工作正常,但我想知道是否有更好的方法來做到這一點?

$totalcollection = ORM::Factory('table')->find_all(); 
// user has an relation named 'activerecords', which will find the records connected 
// to a user through a link table 
$activecollection = $user->activerecords->find_all(); 


foreach($totalcollection as $record) { 

    $active = false; 

    // I'm looking for a function like this one. Does it exist? 
    $active = $activecollection->contains($record); 

    if($active) { 
     echo "<li class=\"active\">".$record->name."</li>"; 
    } else { 
     echo "<li>".$record->name."</li>"; 
    } 
} 

任何想法?

回答

0

你可以寫一個方法,你Model_Table

public function belongs_to_user(Model_User $user) 
{ 
    return ($user->activerecords->where('id', '=', $this->id)->count_all() > 0); 
} 

,然後在循環

foreach($totalcollection as $record) { 

    if($record->belongs_to_user($user)) { 
     echo "<li class=\"active\">".$record->name."</li>"; 
    } else { 
     echo "<li>".$record->name."</li>"; 
    } 
} 

另一種選擇,如果你認爲這會產生太多的SQL查詢,將獲取activerecord ID並與in_array()覈對,我認爲這就是你現在正在做的事情。海事組織也會很好。

順便說一句:請考慮從你的邏輯分離你的佈局,例如與KOstache

+0

感謝您的反饋!我確實希望已經有這樣的功能,你的回答會增加很多查詢,所以我想我會堅持當前的邏輯。我使用smarty,所​​以佈局和邏輯是分開的。但對於這個例子來說,這更簡單。不管怎麼說,還是要謝謝你! – mrBrown 2013-02-11 14:04:50

0

由於您使用單一的表,你只需要檢查從$totalcollection元素的type屬性是否等於active,像這樣:

$totalcollection = ORM::Factory('table')->find_all(); 

foreach($totalcollection as $record) { 

    if($record->type == 'active') { 
     echo "<li class=\"active\">".$record->name."</li>"; 
    } else { 
     echo "<li>".$record->name."</li>"; 
    } 
} 

將它們作爲兩個單獨集合是沒有意義的,並是不必要的開銷。

+0

我的歉意,我的示例代碼有點窮..我修改它。有一個鏈接表連接用戶和記錄,1-n關係。我想查找所有記錄,然後檢查哪一個連接到用戶。現在更清楚了嗎? – mrBrown 2013-02-11 12:53:13