访问cakephp3控制器中的非关联表

时间:2018-05-27 12:59:29

标签: mysql associations cakephp-3.x

我是cakephp3的新手,我正试图访问"表A"没有链接到"表B"在表2的控制器中

我想在UsersController中使用用户类别表。如何实现?

e.g。

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

1 个答案:

答案 0 :(得分:0)

在控制器中,您可以使用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']);
    }

}