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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码