Kohana 3.2 ORM检查集合中是否存在记录


Kohana 3.2 ORM check if a record exists in a collection

我正在尝试打印一个包含记录的总列表,对于这个列表,有些记录可能连接到了用户。活动项来自同一类的另一个集合(活动集合)。我将预览整个列表,并需要检查每个记录是否在活动集合中消失。有这样的功能吗?

目前,我将活动项放在一个数组中,并将记录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>";
   }
}

有什么想法吗?

您可以在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查询,那就是获取活动记录ID并使用in_array()进行检查,我认为这就是你目前的做法。也可以,IMO.

BTW:请考虑将您的布局与逻辑分离,例如使用KOstache。

由于使用的是单个表,因此只需要检查$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>";
   }
}

将它们视为两个独立的集合毫无意义,而且是不必要的开销。