在CakePHP中使用函数定义虚拟字段值


Using functions to define virtual field values in CakePHP

我想做这样的事情(所有这些代码都将在模型中,自然):

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...
    }
}

是否有任何方法在模型中做到这一点,或者我真的需要在飞行中创建这个虚拟字段?

对于虚拟字段可以这样做:

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不是很熟悉,但这应该是你要找的。

如果您想在模型中使用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;
}

如果您需要对quantitytype执行逻辑,我建议使用afterFind代替。