cakePHP得到self hasMany数组

时间:2010-06-08 06:32:33

标签: cakephp

我的表格中包含以下字段:
empid,empname,empcode,department_id ...


我需要一个类似的数组 [模型]
------- [ department_id 1 ]
-------------- [0]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

-------------- [1]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

-------------- [2]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]


------- [ department_id 2 ]
-------------- [0]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

-------------- [1]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

-------------- [2]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

------- [ department_id 3 ]
-------------- [0]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]

-------------- [1]
-------------------- [EMPID]
-------------------- [empname]
-------------------- [empcode]


此致

2 个答案:

答案 0 :(得分:1)

你应该寻找Set :: combine函数:

http://book.cakephp.org/view/662/combine

您的确切解决方案(基于您的示例):

$employees = $this->Employee->find('all');
$result = Set::combine(
    $employees, 
    '/Employee/empid', 
    '/Employee', 
    '/Employee/department_id');

希望这有帮助

答案 1 :(得分:0)

您的“部门”和“员工”实体似乎有一对多的关系。所以最好把桌子分成两部分。为Department提供一个表,为Employee提供另一个表。然后,部门ID将成为Employee表上的外键。

例如,

“部门”表: - id,department_name,..

“员工”表: - id,emp_name,emp_code,...,department_id(外键)

详细了解模特关系: http://book.cakephp.org/view/79/Relationship-Types