首页 > 解决方案 > Cake php 表连接两个字段

问题描述

我从使用 Cakephp 4.x 的 php 开始。

我烤了一张名为Persona(西班牙语为人)的表,有两个字段,last_namesnames.

我设置了setDisplayField我的PersonaTabletolast_names但我想加入它names,所以输出将是:

Doe, John

相关代码:

public function initialize(array $config): void
{
    parent::initialize($config);

    $this->setTable('personas');
    
    /* 
     * here I want to join last_names with names
     */
    $this->setDisplayField('last_names');
    $this->setPrimaryKey('id');
}

我的猜测是我必须在我的函数中创建一个PersonaTable给出该结果的函数,但我不知道从哪里开始。

标签: phpcakephp

解决方案


答案是Virtual entity fields

将此功能添加到模型中

protected function _getFullName() {
    return $this->first_name . ' ' . $this->last_name;
}

我可以full_name作为一个字段访问,例​​如:

$persona->full_name

推荐阅读