CakePHP 3中的子查询?

时间:2015-11-24 02:51:48

标签: cakephp subquery conventions cakephp-3.1 cakephp-3.x

根据CakePHP BelongsToMany约定,我有两个表productsproduct_categories通过第三个表products_categories_products关联(编辑:这些关联在ProductsTable.php中建立和ProductCategoriesTable.php)。我想生成一个产品类别列表,使用最畅销产品中的图像来表示每个类别。

我可以使用以下功能实现我想要的结果:

public function findImages(Query $query, array $options) {
    $query->select([
        'ProductCategories.id',
        'ProductCategories.name',
        'ProductCategories__image' => '(SELECT Products.image
        FROM product_categories_products AS ProductCategoriesProducts
        LEFT JOIN products AS Products
        ON ProductCategoriesProducts.product_id = Products.id
        WHERE ProductCategoriesProducts.product_category_id = ProductCategories.id
        ORDER BY Products.turnover DESC
        LIMIT 1)'
    ])->where([
        'ProductCategories.name <>' => 'Unsorted'
    ])->order([
        'ProductCategories.name'    => 'asc'
    ]);
    return $query;
}

这是否可以接受或是否有实现目标的方式?我无法在CakePHP 3中找到关于制作子查询主题的任何内容。我在几个小时的挫折之后偶然发现了上述解决方案。任何建议表示赞赏!

1 个答案:

答案 0 :(得分:4)

感谢用户ndm_yesterday的链接,我生成了以下解决方案:

public function findImages(Query $query, array $options) {
    $this->hasMany('ProductCategoriesProducts');

    $subquery = $this->ProductCategoriesProducts->find('all')->select([
        'Products.image'
    ])->join([
        [
            'table'     => 'products',
            'alias'     => 'Products',
            'type'      => 'LEFT',
            'conditions'=> [
                'ProductCategoriesProducts.product_id = Products.id'
            ]
        ]
    ])->where([
        'ProductCategoriesProducts.product_category_id = ProductCategories.id'
    ])->order([
        'Products.turnover' => 'DESC'
    ])->limit(1);

    $query->select([
        'ProductCategories.id',
        'ProductCategories.name',
        'ProductCategories__image' => $subquery
    ])->where([
        'ProductCategories.name <>' => 'Unsorted'
    ])->order([
        'ProductCategories.name'    => 'asc'
    ]);

    return $query;
}