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

从另一个表中获取另一个字段的值? 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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化