简体   繁体   中英

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)); 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::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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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