简体   繁体   English

锂applyFilter(find)用于相关模型

[英]Lithium applyFilter(find) for related models

One model belongs to other. 一个模型属于其他模型。 I need to apply "after find" filter in child model, so I try to do: 我需要在子模型中应用“找到后”过滤器,所以我尝试这样做:

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;
});

Then I try to find all parents with Parent::all(array('with' => 'Child', 'conditions' => $conditions)); 然后我尝试使用Parent::all(array('with' => 'Child', 'conditions' => $conditions));查找所有父母Parent::all(array('with' => 'Child', 'conditions' => $conditions)); and filter doesn`t apply :( What can be done? 和过滤器不适用:(可以做什么?

I think what you are looking for is a filter on the Parent find method: 我认为您正在寻找的是对Parent查找方法的过滤器:

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;
});

I'm not sure why you expect this to work. 我不确定您为什么期望此方法有效。 Filters act on the class methods you apply them to. 过滤器作用于您将它们应用到的类方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM