0

我正在尝试在模型中动态设置一个字段,因此它会在我的任何读取操作中返回。我查看了虚拟字段,但它们并不完全正确,因为它们基本上执行 SQL 查询。

在这个例子中,我试图根据一个简单的检查返回一个值,以查看用户是否激活了他们的帐户。在我的模型中,我想运行这个函数:

public function status() {
    if ($this->field('password')) {
        return = 'active';
    } else if ($this->Ticket->field('id')) {
        return = 'pending';
    } else {
        return = 'inactive';
    }
}

目的是通过 $user['User']['status'] 在我的视图中访问它,因此我可以根据结果应用 CSS 样式等。

但是在设置 $this['User']['status'] = status() 之间,我现在正在逃避。

此外,由于我正在以不同的方式阅读我的用户列表(有时使用分页,或者一次一个用户),这不是我想在我的控制器中设置的东西。我希望该属性在读取时简单地出现在模型中。

4

2 回答 2

2

如何执行您的逻辑并将其附加到afterFind回调的结果中?(它的名字是在你做 a 之后触发的find())像这样的东西:

//User model
public function afterFind($results) {

    if ($this->field('password')) {
        $results[$this->alias]['status'] = 'active';

    } else if ($this->Ticket->field('id')) {
        $results[$this->alias]['status'] = 'pending';

    } else {
        $results[$this->alias]['status'] = 'inactive';
    }
}
于 2012-05-02T13:55:35.647 回答
0

在要调用状态函数的回调中尝试此操作:

$this->data[$this->alias]['status'] = $this->status();
于 2012-05-02T13:47:20.693 回答