在选择字段时,我在尝试获取关联模型时遇到了一些麻烦。我的 CakePHP 版本是 3.0beta2。
与此问题相关的三个 MYSQL 表:
users:
`id` int(11) NOT NULL,
`username` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`role` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
... (more information)
-
presets:
`id` int(11) NOT NULL,
`name` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(11) NOT NULL,
... (more information)
-
favorites:
`id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`preset_id` int(11) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
我的关联定义如下所示:
// From FavoritesTable.php
public function initialize(array $config) {
$this->belongsTo('Users');
$this->belongsTo('Presets');
}
// From PresetsTable.php
public function initialize(array $config) {
$this->belongsTo('Users');
$this->hasMany('Favorites');
}
// From UsersTable.php
public function initialize(array $config) {
$this->hasMany('Presets');
$this->hasMany('Favorites');
}
我想要实现的是:
- 加载当前登录用户的所有用户信息
- 加载该用户拥有的所有收藏夹
- 创建一个将
created
字段(时间戳)转换为日期的新字段 - 对于每个收藏夹,加载关联的预设数据
这是我用来执行此操作的代码:
// From UsersController.php
public function favorites() {
$userId = $this->Auth->user('id');
$user = $this->Users->find('all')
->where(['id' => $userId])
->contain([
'Favorites' => function($q) {
return $q
->select(['id', 'preset_id', 'user_id', 'created', 'date' => 'DATE(created)'])
->order(['Favorites.created' => 'DESC']);
},
'Favorites.Presets',
])
->first();
$this->set('user', $user);
}
问题是:当我使用select
上面代码中的方法时,Favorites.Presets
没有加载关联,所以$user['favorites'][0]['preset']
总是null
.
但是,如果我注释掉 select 方法(从而选择所有字段而不是检索DATE(created)
,则加载关联,我可以访问预设表中的信息。
这可能是一个错误还是我做错了什么?
谢谢您的帮助!