1

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

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

例如,我的数据库中没有name和字段,而是有 posh_name、cheap_name、posh_description 和cheap_description。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;
}

这仅在直接从模型访问数据时有效,在通过模型关联访问数据时无效。

必须有办法让它正常工作。如何?

4

2 回答 2

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 不是可以回来咬我的不可以?

于 2011-02-23T17:05:29.853 回答
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'
);
于 2011-02-23T16:55:48.760 回答