我一直在CakePHP 2.6中开发一个应用程序,其中一名工作人员最初只属于一个部门,但系统要求现在已经改变,并且工作人员和部门之间存在HasAndBelongsToMany(HABTM)关系。
现在证明这是一个问题,我只向那些属于视图中某个部门的工作人员显示信息,因为我的AuthComponent :: user()对象现在包含一系列部门。
是否有一种简单的方法可以遍历AuthComponent :: user()Department数组并检查某个值是否与所选值匹配?
HABTM关系之前的旧视图代码:
if (AuthComponent::user('admin') == 1 || (AuthComponent::user('department_id') == $department['Department']['id'])) {
// Some code here
};
AuthComponent :: user()数组:
array(16) {
["id"]=>
string(1) "6"
["salutation"]=>
string(2) "Mr"
["firstname"]=>
string(6) "Joe"
["lastname"]=>
string(4) "Bloggs"
["email"]=>
string(21) "joe.bloggs@email.com"
["role"]=>
string(23) "Teacher"
["admin"]=>
bool(true)
["dos"]=>
bool(false)
["school_id"]=>
string(1) "1"
["active"]=>
bool(true)
["School"]=>
array(2) {
["id"]=>
string(1) "1"
["name"]=>
string(10) "School Name"
}
["Department"]=>
array(3) {
[0]=>
array(2) {
["id"]=>
string(1) "4"
["name"]=>
string(20) "Careers & University"
}
[1]=>
array(2) {
["id"]=>
string(2) "14"
["name"]=>
string(9) "Geography"
}
[2]=>
array(2) {
["id"]=>
string(2) "16"
["name"]=>
string(3) "ICT"
}
}
}
答案 0 :(得分:2)
最简单的方法可能是使用CakePHP's Hash::extract()
方法构建属于该用户的所有部门的简单数组,然后检查该部门中是否存在这样的部门: -
$user = AuthComponent::user();
$departments = Hash::extract($user, 'Department.{n}.id');
if (
(int)$user['admin'] === 1
|| in_array($department['Department']['id'], $departments) === true
) {
// Some code here
}
CakePHP中的Hash实用程序值得一看,因为它提供了一些非常方便的数组操作方法,可以处理find()
查询返回的数组。
答案 1 :(得分:0)
有许多不同的方法可以做到这一点。你可以编写一个循环的函数 - 并且很容易实现:
function doesBelongToDepartment($deptList, $userDeptId)
{
foreach($deptList as $dept) {
if($dept['id'] == $userDeptId) return true;
}
return false;
}
然后你可以像下面一样使用它:
if (AuthComponent::user('admin') == 1 || doesBelongToDepartment($department['Department'], AuthComponent::user('department_id'))) {