我需要在我的用户实体中拥有一个虚拟属性(property)。我关注了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'];
}
}
在 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
我完全按照书上的要求做了,我只得到了一个null
值。
最佳答案
根据@ndm 的说法,问题是由于错误的文件命名造成的。我将用户实体类命名为 UserEntity.php
。 The CakePHP name conventions说:
The Entity class OptionValue would be found in a file named OptionValue.php.
谢谢。
关于php - Cakephp 3 的虚拟字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31437227/