【发布时间】:2017-07-31 09:41:12
【问题描述】:
我有一个简单的表格结构:
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。
我确定存在与现有user_id 相关的行(在表programs 中),与users.id 相关,并且我确定实体加载成功。
如何使用外键访问?
P.S ProgramsTable
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。
P.P.S 例如(在用户控制器中)
$SomeSuccessfullyLoadedUser= $this->Users->get($this->Auth->user()['id']);
debug($SomeSuccessfullyLoadedUser->email); //prints user's email
debug($SomeSuccessfullyLoadedUser->programs); //prints 'null'
【问题讨论】:
-
分享你的 ModelsController.php 和你的 ModelsTable.php
-
你的问题没有明确定义!
-
@Christian,我补充说。
-
就像@MazbaKamal 所说,您的问题没有明确定义。你的桌子看起来不错。不知道您所说的 $SomeSuccessfullyLoadedUser 是什么意思。您想获取包含该用户程序的登录用户吗?
-
@MazbaKamal,我添加了说明。
标签: mysql cakephp foreign-keys cakephp-3.0 cake-bake