【问题标题】:Create virtual field in constructor from an existing field从现有字段在构造函数中创建虚拟字段
【发布时间】:2017-10-19 11:13:11
【问题描述】:

我有这个模型叫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', 
)));

【问题讨论】:

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

标签: php sql cakephp cakephp-2.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) ;
}

我已包含用于动态生成模型名称的代码,因此它也适用于别名,如 CakePHP 2.x: Virtual fields and model aliases 中所述。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2019-09-25
    相关资源
    最近更新 更多