“fields”查找条件中的虚拟字段- Cakephp

oyxsuwqo  于 2022-11-12  发布在  PHP
关注(0)|答案(3)|浏览(143)

我有一个带有虚拟字段的Student模型:

var $virtualFields = array(
    'full_name' => 'CONCAT(Student.fname, " ", Student.lname)'
);

我正在执行查找操作,以使用“fields”获取特定字段:

$this->Student->find('all', array('fields' => array('Student.fname','Student.lname')));

由于某种原因,在找到记录后没有创建虚拟字段。我试着添加Student.full_name,但当然它在mysql中给出了unknown column错误。
有什么想法吗?

vdgimpew

vdgimpew1#

你不能在字段中指定一个虚拟字段,你需要在没有字段选项的情况下调用它,所以它会把它和结果一起带来...你可能想读一下examples in the cookbook
调用所有字段是一个选项,另一个选项是调用字段选项中的字段,如下所示

$this->Student->find('all', array('fields' => array(
    $this->student->virtualFields['full_name'].'AS Student__full_name',
    'Student.fname','Student.lname')
));
xfb7svmp

xfb7svmp2#

在你的app_model. php中放置一个方法怎么样:

/**
 * combine virtual fields with fields values of find()
 * USAGE:
 * $this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')));
 * @param array $virtualFields to include
 */
public function virtualFields($fields = array()) {
    $res = array();
    foreach ((array)$fields as $field) {
        //TODO: if key numeric => value sql!
        //TODO: allow combined/other models via Model.field syntax
        $sql = $this->virtualFields[$field];
        $res[] = $sql.' AS '.$this->alias.'__'.$field;
    }
    return $res;
}

然后像这样使用它:

$this->Model->find('all', array('fields' => $this->Model->virtualFields('full_name')))

));
或这样:

$fields = $this->Model->virtualFields('full_name');
$fields = am($fields, 'status', 'created');
$this->Model->find('all', array('fields' => $fields));

));

ruoxqz4g

ruoxqz4g3#

在CookBook上:http://book.cakephp.org/2.0/en/models/virtual-fields.html
它说你可以这样使用它:
产品型号:

public $virtualFields = array(
'name' => 'CONCAT(User.first_name, " ", User.last_name)');

控制器或视图:

$results = $this->User->find('first');

结果:

array(
    [User] 
        [first_name] => 'Mark',
        [last_name] => 'Story',
        [name] => 'Mark Story',
        //more fields.
    )

因此,您可以像这样使用它:

$this->set('list_fields', $this->User->find('list', 
array('fields' => array('first_name', 'last_name', 'name'), 
'recursive' => -1, 'condition' => ...)));

相关问题