2013-07-04 49 views
0

一个型号属于其他型号。我需要“后查找”,在子模型过滤器适用,所以我尝试做?锂过滤器(查找)相关型号

class Parent extends \lithium\data\Model 
{ 
    public $hasMany = array(
     'Childs' => array(
     'to' => 'app\models\Child', 
     'key' => array('parent_id' => 'parent_id'), 
    ), 
    ); 
} 
// ... 

class Child extends \lithium\data\Model 
{ 
    protected $_meta = array(
     'source' => 'child', 
     'key' => 'child_id', 
    ); 

    public $belongsTo = array(
     'Parent' => array(
      'to' => 'app\models\Parent', 
      'key' => 'parent_id', 
     ) 
    ); 
} 

Child::applyFilter('find', function($self, $params, $chain) 
{ 
    $entity = $chain->next($self, $params, $chain); 

    if (is_object($entity)) 
    { 
     $entity->notes = empty($entity->notes) ? array() : unserialize($entity->notes); 
    } 
    return $entity; 
}); 

然后我试图找到所有家长Parent::all(array('with' => 'Child', 'conditions' => $conditions));和过滤应用`吨:( 什么可以做

回答

0

我不知道你为什么想到这个工作的过滤器作用于类的方法应用它们来

+0

Child :: applyFilter('find') - 这不适用于查找方法吗? – Crusader

+0

应用于'Parent :: find()'的过滤器适用于'Parent :: find()'。应用于'Child :: find()'的过滤器适用于'Child :: find()'。你的代码所暗示的是,你正在对'Child'应用一个过滤器,并期望在你调用'Parent'时应用它。我真的不知道你在哪里得到这个应该工作的想法。 –

+0

我希望应用于子项的筛选器即使在表单父项 - >子项中也适用于每个子项。当我做'Parent :: find()'并且得到实体的列表parent-> child时,我想让孩子与我直接使用Child :: find相同。父母 - >孩子没有被过滤的意义是什么? – Crusader

1

我想你正在寻找的是在家长find方法的过滤器:。

Parent::applyFilter('find', function($self, $params, $chain) 
{ 
    $result = $chain->next($self, $params, $chain); 

    if (isset($params['options']['with']) && $params['options']['with'] === 'Child') { 
     $result = $result->map(function($parent) { 
      if ($parent->child) { 
       $child = &$parent->child; 
       $child->notes = empty($child->notes) ? array() : unserialize($child->notes); 
      } 

      return $parent; 
     }); 
    } 

    return $result; 
});