doudao5287
2013-03-25 15:41
浏览 45
已采纳

从另一个表中获取另一个字段的值? CakePHP的

I have two tables, departments and users. On users, I have the following fields:

id | username | password | email | department | date_created

Now on departments, I have the following fields:

id | name

The department field on the users table is INT and it points to the corresponding id on the departments table. How do I retrieve the corresponding name to display on the department field when rendered on the web? I tried doing this but it doesn't seem to work.

class UsersController extends AppController {

    public function index() {
        $this->set('users', $this->User->find('all'));

        $departmentsArray = array();
        $departments = $this->Department->find('all');
        foreach ($departments as $department) {
            $departmentsArray[$department['Department']['id']] = $department['Department']['name'];
        }
        $this->set('departments', $departmentsArray);
    }

}

I am supposedly going to use it to retrieve the data on View\Users\index.ctp. However, it gives me an error:

Error: Call to a member function find() on a non-object 
File: D:\serveroot\app\Controller\UsersController.php 
Line: 11

Line 11 is $departments = $this->Department->find('all'); from the first code block I gave above.

Sorry if this seems all too complicated, if there's a simpler way to approach this, please do tell me. I guess to put it simply, I need to retrieve data in a table via an id defined from another table.

EDIT:

Additional info from Hyarion, instead of using find('all') I used find('list') so I reduced the lines of code from 6 to 1! :) Here's the new code:

class UsersController extends AppController {
    var $uses = array('User', 'Department');

    public function index() {
        $this->set('users', $this->User->find('all'));

        $this->set('departments', $this->Department->find('list'));
    }

}
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douan4347 2013-03-25 15:47
    已采纳

    You need to tell your controller to load the model for Departments as well. By default it is only loading Users.

    Add this to the top of your controller:

    var $uses = array('User', 'Department');
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题