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));并且过滤器不适用:(可以做什么?

4

2 回答 2

1

我认为您正在寻找的是 Parent 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;
});
于 2014-01-10T13:56:11.810 回答
0

我不知道你为什么希望这能奏效。过滤器作用于您应用它们的类方法。

于 2013-07-04T20:45:30.670 回答