2017-07-18 31 views
0

我有一個roles表。看起來是這樣的:Cakephp 3創建條目,設置自定義主字段

CREATE TABLE `roles` (
    `role` varchar(20) COLLATE utf8_unicode_ci NOT NULL, 
    `permissions` longtext COLLATE utf8_unicode_ci 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 
ALTER TABLE `roles` 
    ADD PRIMARY KEY (`role`), 
    ADD UNIQUE KEY `role` (`role`); 

現在蛋糕是不承認它作爲一個「正常」的領域,所以它沒有給出任何輸入欄。

我固定我的這個觀點:

// src/Template/Admin/Roles/add.ctp 

echo $this->Form->control('name', ['class' => 'form-control']); 

現在在我的控制器解決方法:

// src/Controller/Admin/RolesController.ctp 

$roleData = $this->request->getData(); 
$roleData['role'] = strtolower($roleData['name']); 
unset($roleData['name']); 

$role = $this->Roles->patchEntity($role, $roleData); 
if ($this->Roles->save($role)) { 
    $this->Flash->success(__('The role has been saved.')); 
} 

它節省的條目,但數據庫行role中不填寫任何東西。我錯過了什麼嗎?

+0

你是否檢查Entity文件夾中的RoleEntity文件,是否可以訪問! –

+0

當您需要重新命名角色時,您會做什麼?如果有外鍵約束,你會怎麼做?順便說一句,主鍵必須是唯一的定義。 – ndm

回答

1

如果您使用的是patchEntity,那麼您無法分配不可分配的字段,並且您的主鍵默認情況下不可能是可分配的鍵。您可以在允許表單顯示的實體中更改它,以允許修補程序實體正常工作。

namespace App\Model\Entity; 

use Cake\ORM\Entity; 

class Role extends Entity 
{ 
    protected $_accessible = [ 
     'role' => true, 
     'permissions' => true, 
     '*' => false, 
    ]; 
} 

https://book.cakephp.org/3.0/en/orm/saving-data.html#changing-accessible-fields

https://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment

+1

首先嚐試,它沒有工作。然後我重新模仿了模型,控制器和視圖。現在它可以工作。謝謝 :) –

0

RolesTable.php應該是這樣的:

public function initialize(array $config) 
{ 
    parent::initialize($config); 
    $this->setTable('roles'); 
    $this->setPrimaryKey('role'); 
} 

這樣的CakePHP會使用'role'作爲PrimaryKey的。