如何限制从CakePHP中的关联表中检索的行数?

时间:2009-11-01 14:54:49

标签: php cakephp

假设有两个数据库表:FundsPrices,其中Funds hasMany Prices

我想要做的是在特定情况下检索特定基金的最新价格。 CakePHP中是否有一种方法可以进行$this->Fund->find('all')调用,以允许我限制从关联的Price表中检索的行数?

请注意,我不想在'limit'模型的Fund变量中设置$hasMany选项。

关于已接受答案的注意事项[11月2日]:

In Jason's answer which I had accepted,我个人选择了bindModel解决方案,因为我觉得尽管感觉有点“hack-y”,但对我来说更好的是在默认情况下进行一次性覆盖模型绑定。

我使用的代码如下:

$this->Fund->bindModel(array(
    'hasMany' => array(
        'Price' => array(
            'limit' => 15,
            'order' => 'Price.date DESC'
        )
    )
);

不需要unbindModel。可以从CakePHP手册中的“3.7.6.6 Creating and Destroying Associations on the Fly”中读取更多信息。

3 个答案:

答案 0 :(得分:2)

您可以使用Containable行为轻松完成此任务。

    您的AppModel或基金模型中的
  • 添加:

    var $actsAs = array('Containable');
  • 然后在您的控制器中,您可以在查找中添加“包含”选项(“全部”):

    $this->Fund->find('all', array(
        'contain' => array(
            'Price' => array(
                'limit' => 15,
                'order' => 'Price.date DESC')
    )));
    

书中提供了更多信息:http://book.cakephp.org/view/474/Containable

答案 1 :(得分:0)

据我所知,您不希望在模型中静态设置限制。如果您希望使用hasMany关联,除了以某种方式更改该限制之外,我确实没有任何其他方式。

以下是动态更改它的几种方法:

  1. 您可以通过调用Funds-> bindModel()来更改限制。 (这可能首先需要一个unbindModel(),但我不记得确定)
  2. 您可以向基金添加功能以直接更改限制。 (见下面的例子。)
  3. 如果您有野心,可以编写一个行为来添加功能,以便按照与the Containable behavior类似的方式为每个find()调用指定它。
  4. #2的示例

    <?php
    function setPriceLimit($limit = 10) {
         // Assuming the association is 'Price'
         $this->hasMany['Price']['limit'] = $limit;
    }
    ?>
    

答案 2 :(得分:0)

您的$ this-&gt;模型 - &gt; find('all')可能包含条件。即

$ this-&gt; Model-&gt; find('all',array('conditions'=&gt; array('Model.field'=&gt; $ value),'limit'=&gt; 15));

有关详情,请查看蛋糕文档。

Retrieving Your Data

相关问题