问题描述
我已经阅读了几篇关于在 CakePHP 3 中保存相关数据的 Stack Overflow 帖子和文档页面,但我无法让我的代码工作。创建新的 Organisation
时,我还想保存属于该 NewAccount
的新帐户 (Organisation
) 的数据。
以下是我的代码的可重现部分。执行组织模型的验证,如果通过,则保存数据。 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'),]);
echo $this->Form->control('name',[
'label' => __('Organisation name'),'div' => 'form-group',]);
// 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 文档:
解决方法
我忘记设置 // Model/Entity/Organisation.php
class Organisation extends Entity
{
protected $_accessible = [
// ...
'new_account' => true,];
}
可访问性:
if (updateShowcasedProducts.length == 12) {
document.querySelectorAll('input[type="checkbox"]').forEach(i => i.disabled = true);
}
通过这样做,该字段被标记为安全分配。
Entities: Mass Assignment (book) 和 EntityTrait::$_accessible (API docs)