使用 Contain 获取数据的最佳规则

Best rules to get data with Contain

在 CakePHP 3 中,ORM 已经改变,我无法从数据库中找到 select 所需数据的正确方法。

在 CakePHP 2 中,我使用 contain('User.name','User.id'),但在 CakePHP 3 中,此代码不起作用。

那么我如何才能 select 仅来自用户的 idname

代码:

$query = $data->find()->contain(['Users'])->execute()->fetchAll('assoc');
// I want only user.id and user.name.
$articles = $this->Model->find()
        ->select(['fields_you_want_from_this_Model'])
        ->contain(['Assoc_Model'  => function($q) {
            return $q
                ->select(['fields_you_want_from_the_associated_model']);
        }]);

你必须看看这个页面:http://book.cakephp.org/3.0/en/orm/query-builder.html#passing-conditions-to-contain

在某些情况下,您必须使用 autoFields 方法。

当你 select 可调用字段很少时要小心包含,你总是必须 select 外键也:

When you limit the fields that are fetched from an association, you must ensure that the foreign key columns are selected. Failing to select foreign key fields will cause associated data to not be present in the final result.