首页 > 解决方案 > 访问 cakephp3 控制器中的非关联表

问题描述

我是 cakephp3 的新手,我正在尝试访问未链接到表 2 控制器中的“表 B”的“表 A”

我想在 UsersController 中使用用户类别表。如何做到这一点?

例如

user table has three fields id, name, role
category table has 2 fields id, name
articles table has 3 fields id, user_id, category_id, article

标签: mysqlassociationscakephp-3.x

解决方案


在您的控制器中,您可以使用loadModel()加载另一个未链接到控制器默认模型的表。

class UsersController extends AppController {

    public function initialize() {
        parent::initialize();
        // You don't have to put it in initiliaze 
        // but if you want to use it in more than one method it's a good place
        $this->loadModel('Categories');
        $this->loadModel('Articles');
    }

    public function index() {
        // Categories is now available as $this->Categories thanks to loadModel()
        $categories = $this->Categories->find()->select(['id', 'name']);
    }

}

推荐阅读