如何显示嵌套关联值cakephp 3

时间:2017-10-11 10:57:03

标签: php cakephp associations query-builder cakephp-3.x

我想运行此代码,它具有嵌套的关联数据:

'VhpProducts.VhpHasilPencapaian',
'Departments.VhpHasilPencapaian',
'Groups.VhpHasilPencapaian' and to sum 'VhpHasilPencapaian.quantity'

但我得到的只是

  

错误:SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'VhpHasilPencapaian.amount'

$vhpCriteria = $this->VhpCriterias->find('all', [
    'contain' => [
        'VhpProducts.VhpHasilPencapaian',
        'Departments.VhpHasilPencapaian',
        'Groups.VhpHasilPencapaian'
    ],
    'field' => ['VhpProducts.name']
]);
$vhpCriteria->select([
    'product' => 'VhpProducts.name',
    'amountTotal' => $vhpHasilPencapaian->func()->sum('VhpHasilPencapaian.amount'),
    'qty' => $vhpHasilPencapaian->func()->sum('VhpHasilPencapaian.quantity'),
]);

2 个答案:

答案 0 :(得分:0)

"嵌套"协会应该写成这样:

    $users = $this
        ->Users
        ->find('all')
        ->contain([
            'Roles' => [
                'Rights'
            ],
            'Posts' => [
                'Comments' => [
                    'Replies' => function($query) {
                        return $query
                            ->where(['public' => 1]);
                    }
                ]
            ]
        ])
    ->toArray();

答案 1 :(得分:0)

您需要选择要使用的所有数据。您的字段应为字段,并包含您要返回的所有字段。或者,您可以完全排除它以返回所有内容。如果您没有在fields选项中指定字段,则不会返回该字段,也不能使用它。

$vhpCriteria = $this->VhpCriterias->find('all', [
    'contain' => [
        'VhpProducts.VhpHasilPencapaian',
        'Departments.VhpHasilPencapaian',
        'Groups.VhpHasilPencapaian'
    ],
    'fields' => ['VhpProducts.name', 'ALL OTHER FIELDS']
]);

$vhpCriteria->select([
    'product' => 'VhpProducts.name',
    'amountTotal' => $vhpHasilPencapaian->func()->sum('VhpHasilPencapaian.amount'),
    'qty' => $vhpHasilPencapaian->func()->sum('VhpHasilPencapaian.quantity'),
]);