一个模型属于其他模型。我需要在子模型中应用“after find”过滤器,所以我尝试这样做:
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 :(得分:1)
我认为您正在寻找的是父查找方法的过滤器:
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;
});
答案 1 :(得分:0)
我不确定为什么你希望这个有效。过滤器会对您应用它们的类方法起作用。