小编Lib*_*tie的帖子

CakePHP 3 中的子查询?

我有两个表productsproduct_categories被通过第三表相关联,products_categories_products根据CakePHP的BelongsToMany约定(编辑:这些关联建立ProductsTable.phpProductCategoriesTable.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;
}
Run Code Online (Sandbox Code Playgroud)

这是可以接受的还是有更简单的方法来实现我的目标?我真的找不到关于在 CakePHP 3 中制作子查询的主题的任何内容。经过几个小时的挫折后,我偶然发现了上述解决方案。任何建议表示赞赏!

cakephp conventions subquery cakephp-3.1 cakephp-3.x

3
推荐指数
1
解决办法
8463
查看次数