2016-12-06 103 views
1

用戶角色我有現有用戶的角色列表中的數據庫,例如像這樣:不能關聯與用戶

+----+-------+-----------+ 
| id | level | label | 
+----+-------+-----------+ 
| 1 |  0 | admin  | 
| 2 |  1 | moderator | 
| 3 |  2 | blogger | 
+----+-------+-----------+ 

而且我想它的創建時給角色附加到用戶。我已經試過是以下幾點:

在我BcUsersController:

$bcUser = $this->BcUsers->patchEntity($bcUser, $this->request->data, 
     [ 
      'associated' => [ 
       'BcUserInfos', 
       'BcUserRoles' 
      ] 
     ] 
    ); 
    if ($this->BcUsers->save($bcUser))... 

協會:

//BcUserRolesTable 
$this->belongsToMany('BcUsers', [ 
    'className' => 'BcUsers', 
    'foreignKey' => 'role', 
    'propertyName' => 'BcUserRoles' 
]); 


//BcUsersTable 
$this->hasMany('BcUserRoles', [ 
    'className' => 'BcUserRoles', 
    'foreignKey' => 'id', 
    'bindingKey' => 'role', 
    'propertyName' => 'BcUserRoles', 
    'joinTable' => 'bc_user_roles' 
]); 

這是我嘗試注入userRoleId到用戶表:

<?= $this->Form->input('BcUserRoles.level', ['type' => 'hidden', 'value' => '0']); ?> 

<?= $this->Form->input('BcUserRoles.id', ['type' => 'hidden', 'value' => '1']); ?> 

當我嘗試保存它時,只是刷新了頁面和頁面數據內部字段,並沒有出現任何錯誤。如果我刪除所有關聯代碼,它將保存user + userInfo。我在這裏錯過了什麼?

編輯

我剛剛發現了一個錯誤,我$bcUser變量:

'[errors]' => [ 
     'role' => [ 
      '_required' => 'This field is required' 
     ] 
    ], 

我想這就是爲什麼它不保存BcUser,也UserRole的協會是空的:

'BcUserRoles' => [], 

所以它不會保存userRole到用戶表,即使我會刪除

->requirePresence('role', 'create') from BcUsersTable,會嗎?

剛剛測試。它會拋出SQL錯誤,因爲角色不在查詢參數中,而在數據庫中它必須在那裏,不允許使用null。所有用戶都應該有一個角色。

+0

您的BcUserRoles是否有與BcUsers一起定義的關聯? – styks

+0

@Kelvin是的,它顯示在代碼 – ksno

+0

的第二部分中,是否閱讀[this](http://book.cakephp.org/3.0/en/views/helpers/form.html#creating-inputs-for-associated-數據)段來自手冊?輸入名稱應該是'bc_user_roles.level'和'bc_user_roles.id'。我也會遵循tarikul05的建議 – arilia

回答

1

看起來這裏有幾個問題。

協會

如果BcUsersTable包含BcUserRoles外鍵,然後它是一個belongsTo關係。

belongsTo:當前模型包含外鍵。

http://book.cakephp.org/3.0/en/orm/associations.html#belongsto-associations

同樣這也意味着BcUserRoleshasMany關係BcUsers不是belongsTo關係。

的hasMany:其它模型包含外鍵。

http://book.cakephp.org/3.0/en/orm/associations.html#hasmany-associations

後數據

我認爲對於BcUserRolesTableBcUsersTable外鍵是role。這意味着您需要提交role的值,即您希望關聯的用戶角色的id

下面將創建一個表單元素來做到這一點:

$this->Form->input('role', ['type' => 'hidden', 'value' => $useRoleId])

哪裏$userRoleId是你想關聯的角色的ID。

1

嘗試更新屬於關聯關係

$this->belongsTo('BcUsers', [ 
     'className' => 'BcUsers', 
     'foreignKey' => 'role', 
     'bindingKey' => 'id', 
     'propertyName' => 'BcUserRoles' 
    ]); 

使其

$this->belongsTo('BcUserRoles', [ 
     'className' => 'BcUsers', 
     'foreignKey' => 'role', 
     'bindingKey' => 'id', 
    ]); 

希望您的問題將得到解決

+0

它沒有用.. – ksno

+0

你應該清除cakephp關係的概念,for刪除錯誤只需使用'$ this-> Form-> input('role',['type'=>'hidden','value'=> 0])' – tarikul05

+0

抱歉它應該是'$ this-> Form->爲管理員和主持人類型用戶輸入('BcUserRoles._ids',['type'=>'hidden','value'=> [0,1]])'' – tarikul05