How to select fields of a contained association?

前提是你 提交于 2019-11-29 12:44:01

You have to configure the containments individually, selecting fields for other containments won't work.

To be exact, you cannot select fields for a containment from anywhere else than the corresponding containment configuration, with the only exception of belongsTo/hasOne associations that are using the join strategy, fields for them can be selected in the select() call of the immediate "parent" query, as these associations are going to be retrieved via a join in that query.

If for example Sites would be a belongsTo association, then you could select the fields for it via the select() call on Orders. If Users would be a belongsTo, but Sites a hasMany, then you could use the select() call for Sites to select fields for Users.

That being said, in your case you either use the queryBuilder option to define callbacks in a nested array structure

contain([
    'Sites' => [
        'queryBuilder' => function ($q) {
            return $q
                ->select([
                    'Sites.id',
                    'Sites.user_id'
                ]);
        },
        'Users' => function ($q) {
            return $q
                ->select([
                    'Users.id',
                    'Users.name',
                    'Users.owner_id',
                    'Users.firstname',
                    'Users.lastname'
                ]);
        }
    ]
])

or, if you don't actually need the query builder, use the fields option

contain([
    'Sites' => [
        'fields' => [
            'Sites.id',
            'Sites.user_id'
        ],
        'Users' => [
            'fields' => [
                'Users.id',
                'Users.name',
                'Users.owner_id',
                'Users.firstname',
                'Users.lastname'
            ]
        ]
    ]
])

See also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!