【发布时间】:2021-04-17 18:38:03
【问题描述】:
我已经阅读了几篇关于在 CakePHP 3 中保存关联数据的 Stack Overflow 帖子和文档页面,但我的代码无法正常工作。在创建新的Organisation 时,我还想保存属于那个Organisation 的新帐户(NewAccount)的数据。
以下是我的代码的可重现部分。执行组织模型的验证,如果通过,则保存数据。 NewAccounts 数据没有被保存,甚至没有被验证。我已经检查了所有这些文件中的命名约定,但我找不到任何可能成为问题的东西。
// Model/Table/OrganisationsTable.php
class OrganisationsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->hasOne('NewAccounts');
}
}
// Model/Table/NewAccountsTable.php
class NewAccountsTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->belongsTo('Organisations', [
'foreignKey' => 'organisation_id'
]);
}
}
// Template/Organisations/admin_add.ctp
echo $this->Form->create($organisation);
echo $this->Form->control('new_account.email', [
'label' => __('Email address'),
'class' => 'form-control',
]);
echo $this->Form->control('new_account.name', [
'label' => __('Name'),
'class' => 'form-control',
]);
echo $this->Form->control('name', [
'label' => __('Organisation name'),
'div' => 'form-group',
'class' => 'form-control',
]);
// Controller/OrganisationsController.php
class OrganisationsController extends AppController
{
public function adminAdd() {
$organisation = $this->Organisations->newEntity();
if($this->request->is('post')) {
$this->Organisations->patchEntity($organisation, $this->request->getData(), [
'associated' => ['NewAccounts']
]);
if ($this->Organisations->save($organisation)) {
$id = $organisation->id;
debug("Success!");
}
else {
debug("Error");
}
}
$this->set(compact('organisation'));
}
}
我参考过的 CakePHP 文档:
【问题讨论】:
-
组织实体中的
new_account“可访问”吗? -
不,不是。感谢格雷格解决它!
标签: php cakephp orm associations cakephp-3.0