CakePHP在运行时更改虚拟字段

时间:2011-02-23 16:43:40

标签: php cakephp cakephp-1.3 class-variables

我有一个多站点应用程序的产品模型。

根据域(站点),我想加载不同的数据。

例如,我的数据库中没有namedescription字段,而是有posh_name,cheap_name,posh_description和cheap_description。

如果我这样设置:

class Product extends AppModel 
{
    var $virtualFields = array(
        'name' => 'posh_name',
        'description' => 'posh_description'
    );
}

然后它始终有效,无论是直接从模型访问还是通过关联。

但我需要根据域不同的虚拟字段。所以首先我创建我的2套:

var $poshVirtualFields = array(
    'name' => 'posh_name',
    'description' => 'posh_description'
);

var $cheapVirtualFields = array(
    'name' => 'cheap_name',
    'description' => 'cheap_description'
);

所以这些是我的2套,但我如何根据域分配正确的?我有一个名为isCheap()的全局函数,它让我知道我是否在低端域。

所以我尝试了这个:

var $virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;

这给了我一个错误。显然你不能像这样在类定义中分配变量。

所以我把它放在我的产品型号中:

function beforeFind($queryData)
{
    $this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;

    return $queryData;
}

仅在从模型直接访问数据时才有效,在通过模型关联访问数据时不起作用。

必须有一种方法可以让它正常工作。怎么样?

2 个答案:

答案 0 :(得分:1)

好吧,如果我把它放在构造函数而不是beforeFind回调中,它似乎有效:

class Product extends AppModel 
{
    var $poshVirtualFields = array(
        'name' => 'posh_name',
        'description' => 'posh_description'
    );

    var $cheapVirtualFields = array(
        'name' => 'cheap_name',
        'description' => 'cheap_description'
    );

    function  __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        $this->virtualFields = isCheap() ? $this->cheapVirtualFields : $this->poshVirtualFields;
    }
}

但是,我不确定这是否是CakePHP no no 可以回来咬我?

答案 1 :(得分:0)

似乎问题可能是模型关联是一个即时构建的模型。例如AppModel

尝试做pr(get_class($ this-> Relation));在代码中查看输出是什么,它应该是您的模型名称而不是AppModel。

也尝试使用:

var $poshVirtualFields = array(
    'name' => 'Model.posh_name',
    'description' => 'Model.posh_description'
);

var $cheapVirtualFields = array(
    'name' => 'Model.cheap_name',
    'description' => 'Model.cheap_description'
);
相关问题