CakePHP 3.4 外键不起作用

CakePHP 3.4 foreign key not work

我有一个简单的结构 tables:

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 usersbin\cake bake model programs 生成 table 和模型 类。

但是$SomeSuccessfullyLoadedUser->programs总是returnnull。 我确定存在与现有 user_id 相关的行(在 table programs 中),与 users.id 相关,并且我确定实体加载成功。

如何使用外键访问?

P.S 程序表

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 中加载程序模型。 UsersController 具有简单的操作,如登录、注册、注销等。没有具体使用 ProgramsModel。

P.P.S 例如(在 UsersController 中)

$SomeSuccessfullyLoadedUser= $this->Users->get($this->Auth->user()['id']);
debug($SomeSuccessfullyLoadedUser->email);      //prints user's email
debug($SomeSuccessfullyLoadedUser->programs);   //prints 'null'

您必须添加 class 名称以包含数组

$SomeSuccessfullyLoadedUser= $this->Users->get($this->Auth->user()['id'],
[
'contain'=>['Programs']
]);

有关详细信息,请使用此 link