在关联模型Cakephp 2.3x HABTM上应用限制 [英] Applying Limit on associated model Cakephp 2.3x HABTM

查看:88
本文介绍了在关联模型Cakephp 2.3x HABTM上应用限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类别模型:

class Category extends AppModel {
    public $displayField = 'name';

//    public $actsAs = array('Containable');

    public $hasAndBelongsToMany = array(
        'Post' => array(
            'className' => 'Post',
            'joinTable' => 'categories_postss',
            'foreignKey' => 'category_id',
            'associationForeignKey' => 'post_id',
            'unique' => 'keepExisting'
        )
    );
}

$params['contain'] = array('Post' => array(
            'limit'=> 3));
        pr($this->Category->find('first',$params)); exit;

它正在获取所有帖子,而不受限制。
我想做的事情:

It is fetching all Posts, irrespective of limit. What I want to do:

我有此页面,其中我列出了所有类别以及与此相关的最新5条帖子。
我想将关联的模型限制为仅5行。

I have this page where I ma listing all the categories and latest 5 posts related to it. I want to limit the associated model to only 5 rows.

有什么想法吗?

推荐答案

可使用的行为未使用



此问题的最可能原因是根本没有使用可使用的行为。

Containable behavior is not in use

The most likely reason for this problem is that the containable behavior is not being used at all.

比较下面的代码示例:

$results = $this->Category->find('first', array(
    'contain' => array(
        'Post' => array(
            'limit' => 3
        )   
    )   
));

没有可遏制的行为,它将生成以下查询:

Without containable behavior, it'll generate the following queries:

SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post` 
    JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...)

具有可控制的行为,它将生成以下查询:

With containable behavior, it'll generate the following queries:

SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post` 
    JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...) LIMIT 3

为此(以及问题中的代码)检查AppModel在 $ actsAs 中是否具有可包含的行为:

Given this (and the code in the question) check that the AppModel has the containable behavior in $actsAs:

<?php
// app/Model/AppModel.php
class AppModel extends Model {
    public $actsAs = array('Containable');
}



是否始终需要限制?



或者,或者另外,您可能希望放置关联定义中的限制-为此,只需定义'limit'键即可:

Limit always required?

Alternatively, or possibly in addition, you may prefer to put a limit in the association definition - To do so just define the 'limit' key:

class Category extends AppModel {

    public $hasAndBelongsToMany = array(
        'Post' => array(
            'limit' => 100, // default to a high but usable number of results
        )
    );
}

这篇关于在关联模型Cakephp 2.3x HABTM上应用限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆