我想做类似的事情(所有这些代码都在模型中,自然而然):
public $virtualFields = array(
'description' => $this->fillDescription()
);
private function fillDescription() {
$type = $this->data['type'];
$quantity = $this->data['quantity'];
switch($type) {
case 'type A':
'This should be a specific description for type A records and this record has quantity:'.$quantity;
break;
case 'type B':
'This should be a specific description for type B records and this record has quantity:'.$quantity;
break;
etc...
}
}
有什么方法在模型中执行此操作,或者我真的需要动态创建此虚拟字段?
答案 0 :(得分:4)
您可以使用虚拟字段执行此操作:
public $virtualFields = array(
'description' => '
CASE
WHEN type = "A" THEN CONCAT("quantity a description ", quantity)
WHEN type = "B" THEN CONCAT("quantity b description ", quantity)
WHEN type = "C" THEN CONCAT("quantity c description ", quantity)
END
'
);
我不熟悉MySQL CASE
,但这应该是您正在寻找的。 p>
如果您想在模型中使用PHP,请在构建模型时执行此操作:
public function __construct($id = false, $table = null, $ds = null) {
$this->virtualFields['description'] = $this->fillDescription();
parent::__construct($id, $table, $ds);
}
private function fillDescription() {
$out = 'CASE';
$out .= ' WHEN type = "A" THEN CONCAT("quantity a description ", quantity)';
$out .= ' WHEN type = "B" THEN CONCAT("quantity a description ", quantity)';
$out .= ' WHEN type = "C" THEN CONCAT("quantity a description ", quantity)';
$out .= ' END';
return $out;
}
如果您需要针对quantity
或type
执行逻辑,我建议改为使用afterFind
。