2017-10-19 158 views
1

创建构造虚拟领域我有这个模型称为Product从现有场

class Product extends AppModel { 

    public function __construct($id = false, $table = null, $ds = null) { 
     parent::__construct($id, $table, $ds); 

     $file_name = (preg_replace('/\\.[^.\\s]{3,4}$/', '', $this->field('product_picture'))); 
     $ext = end((explode(".", $this->field('product_picture')))); # extra() to prevent notice 
     $this->virtualFields['product_picture_thumbnail'] = $file_name."350x350.".$ext; 
    } 
} 

它有一个域名为product_picture这是像img1.png。我想创建一个基于该名称创建的虚拟字段,其代表类似img1350x350.png

所以当我查询时,它会返回一个空列表。

$this->Product->find('all', array(
    'fields' => array(
     'product_picture', 
     'product_picture_thumbnail', 
))); 
+0

我想知道你是否设法在下面尝试我的答案。 –

回答

1

您正在将PHP代码与SQL代码混合使用。虚拟字段只有在数据库可以解析时才会起作用。

如果你正在使用MySQL,下面应该工作:

public function __construct($id = false, $table = null, $ds = null) { 

    parent::__construct($id, $table, $ds); 

    $this->virtualFields['product_picture_thumbnail'] = sprintf(' 
     CONCAT(
      SUBSTRING_INDEX(%s.product_picture,".",1), 
      "350x350.", 
      SUBSTRING_INDEX(%s.product_picture,".",-1) 
     )', 
     $this->alias, $this->alias) ; 
} 

我已经包含代码dyamically生成模型名称,因此,它也有别名的作品,如CakePHP 2.x: Virtual fields and model aliases描述。