Crusader
Crusader

Reputation: 1200

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?

Upvotes: 0

Views: 327

Answers (2)

aszabo
aszabo

Reputation: 26

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

Upvotes: 1

Nate Abele
Nate Abele

Reputation: 5770

I'm not sure why you expect this to work. Filters act on the class methods you apply them to.

Upvotes: 0

Related Questions