【问题标题】:CakePHP multi-HABTM associations with paginationCakePHP 与分页的多 HABTM 关联
【发布时间】:2011-06-29 20:28:11
【问题描述】:

对于我正在构建的电子商务应用程序,我使用的是 CakePHP。 我创建了数据库,然后用cake bake 烘焙了我的应用程序。 我的模型都正确链接如下:

Product hasMany CategoryProduct,ImagesProduct

Category hasMany CategoryProduct

CategoryProduct belongsTo Product,Category

Image hasMany ImagesProduct

ImagesProduct belongsTo Product,Image

我已尝试以各种方式获取依赖于 category_id 的产品的分页视图,但均未成功。 我设法获得了我想要的数组 $this->CategoryProducts->findByCategoryId($id),但我不能将 cakePHP 的内置分页器与结果数组一起使用。

有人能告诉我如何正确地制定$options['joins'] 数组以传递给分页函数以获得相同的结果,但以分页方式?

我想要做的 SQL 是这样的:

SELECT p . * , i.filename FROM products p LEFT JOIN ( category_products cp, categories c, images_products ip, images i ) ON ( cp.product_id = p.id AND c.id = cp.category_id AND c.id =2 AND ip.product_id = p.id AND ip.image_id = i.id )

【问题讨论】:

    标签: cakephp pagination cakephp-1.3 has-and-belongs-to-many


    【解决方案1】:

    这是一个困扰我很长时间的问题。如果您使用与 CakePHP 的 HABTM 关联,​​则不必将您的任何一个连接模型(CategoryProduct、ImagesProduct)直接关联到您的模型。 cake bake 如果您的表名不太正确,则可能没有正确选择 HABTM 关联。连接表应该是categories_productsimages_products,这将使连接模型CategoriesProductImagesProduct

    不管怎样,以下内容应该可以让您继续按类别进行过滤:

    //in products_controller.php:
    
    //Fake a HasOne association, setting the reset parameter to false since pagination
    //requires two queries to complete (one for the count, one for the data)
    
    $this->Product->bindModel(array(
        'hasOne' => array(
            'CategoriesProduct
        )
    ), false);
    
    //Group by products since the HasOne will return multiple rows for each product
    
    $options = array(
        'group' => 'Product.id',
        'conditions' => array(
            'CategoriesProduct.category_id' => $categories
        )
    );
    
    //To paginate the result:
    
    $this->paginate = $options;
    $products = $this->paginate();
    

    在此示例中,$categories 可以是单个 category_id 或包含 category_ids 的数组(即 array('1', '2', '3'))。结果将是类别的“或”。如果您希望按“AND”类型条件进行过滤,请查看http://edblogs.cal.msu.edu/devteam/2011/02/08/cakephp-habtm-searches/

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多