我有一个简单的表格结构:
CREATE TABLE `programs` (
`id` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`key` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`user_id` int(30) DEFAULT NULL,
`installation_date` date DEFAULT NULL,
`activation_date` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `users` (
`id` int(30) NOT NULL,
`email` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) NOT NULL,
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`second_name` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(30) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`activated` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `programs`
ADD PRIMARY KEY (`id`),
ADD KEY `user_id` (`user_id`) USING BTREE;
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `email` (`email`);
PHPMyAdmin 方案: scheme
然后,我通过bin\cake bake model users
和生成表和模型类bin\cake bake model programs
。
但$SomeSuccessfullyLoadedUser->programs
总是返回null
。我确定存在行(在表中programs
)与现有的user_id
、相关的users.id
,并且我确定实体加载成功。
我应该怎么做才能使用外键访问?
PS 程序表
class ProgramsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('programs');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Users', [
'foreignKey' => 'user_id'
]);
}
//validationDefault
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['user_id'], 'Users'));
return $rules;
}
}
用户标签
class UsersTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->setTable('users');
$this->setDisplayField('name');
$this->setPrimaryKey('id');
$this->hasMany('Programs', [
'foreignKey' => 'user_id'
]);
$this->hasMany('SupportTickets', [
'foreignKey' => 'user_id'
]);
}
//validationDefault
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->isUnique(['email']));
return $rules;
}
我的应用不需要 ProgramsController,我在 AppController 中加载 Programs 模型。UsersController 具有简单的操作,如登录、注册、注销等。没有特定于使用 ProgramsModel。
PPS 例如(在用户控制器中)
$SomeSuccessfullyLoadedUser= $this->Users->get($this->Auth->user()['id']);
debug($SomeSuccessfullyLoadedUser->email); //prints user's email
debug($SomeSuccessfullyLoadedUser->programs); //prints 'null'