CakePHP 3. 可容纳 select

CakePHP 3. Containable select

我有一个多对多关系,其中 TrainingPrograms 可以包含许多练习。它们通过链接 table ExercisesTrainingPrograms.

链接

我想 select 我练习中的某些字段:

$trainingPrograms = $this->TrainingPrograms->find()
            ->contain(['Exercises' => function ($q) {
                return $q
                    ->select(['id','name','description']);
            }
            ])
            ->select(['id','name','description'])
            ->where(['user_id' => $this->Auth->user('id')]);

我得到的结果是这样的:

   "trainingPrograms": [
            {
                "id": 1,
                "name": "Monday Madness",
                "description": "hes",
                "exercises": [
                    {
                        "id": 2,
                        "name": "Barbell Bench Press",
                        "description": "Medium grip ",
                        "exercise_categories_id": 2,
                        "exercise_difficulties_id": 1,
                        "created": "2015-09-16T07:07:01+0000",
                        "modified": "2015-09-16T07:07:01+0000",
                        "_joinData": {
                            "exercise_id": 2,
                            "id": 28,
                            "training_program_id": 1,
                            "created": "2015-10-07T15:45:49+0000"
                        }
                    },
                    {
                        "id": 2,
                        "name": "Barbell Bench Press",
                        "description": "Medium grip ",
                        "exercise_categories_id": 2,
                        "exercise_difficulties_id": 1,
                        "created": "2015-09-16T07:07:01+0000",
                        "modified": "2015-09-16T07:07:01+0000",
                        "_joinData": {
                            "exercise_id": 2,
                            "id": 35,
                            "training_program_id": 1,
                            "created": "2015-10-07T19:58:12+0000"
                        }
                    }
                ]
            }]

如您所见,我得到了练习的所有字段 table,而不是我要求的字段。为什么会这样,我做错了什么?

belongsToMany 关联会启用 Query::autoFields(),以防未通过 fields 选项定义任何字段。这是必要的,因为外键 (exercise_id) 被添加到 SELECT 子句,否则将导致没有其他字段被选择(不确定在哪个上下文中这实际上是必需的)。

Source > \Cake\ORM\Association\BelongsToMany::_buildQuery()

稍后将调用所包含关联的回调,因此您必须禁用 autoFields() 才能通过查询生成器限制所选字段。

->contain(['Exercises' => function ($q) {
    return $q
        ->select(['id','name','description'])
        ->autoFields(false);
}

我无法确定这是否是预期的行为。你可能想打开一个问题 over at GitHub 来澄清,或者在 IRC 上提问。