Virtual fields with Cakephp 3

孤者浪人 提交于 2019-12-21 04:49:22

问题


I need to have a virtual property in my user entity. I followed the CakePHP book.

UserEntity.php

namespace App\Model\Entity;

use Cake\ORM\Entity;

class User extends Entity {

    protected $_virtual = ['full_name'];

    protected function _getFullName() {
        return $this->_properties['firstname'] . ' ' . $this->_properties['lastname'];
    }
}

In a controller

$users = TableRegistry::get('Users');
$user = $users->get(29);
$firstname = $user->firstname; // $firstname: "John"
$lastname = $user->lastname; // $lastname: "Doe"
$value = $user->full_name; // $value: null

I followed exactly the book and I only get a null value.


回答1:


According to @ndm, the problem was due to a bad file naming. I named the user entity class UserEntity.php. The CakePHP name conventions says that:

The Entity class OptionValue would be found in a file named OptionValue.php.

Thanks.




回答2:


Why not just go for something like this?

/*
 * Return Fullname
 */
public function getFullname()
{
    $name = $this->firstname . ' ' . $this->lastname;
    return $name;
}


来源:https://stackoverflow.com/questions/31437227/virtual-fields-with-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!