假设有两个数据库表:Funds
和Prices
,其中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”中读取更多信息。
答案 0 :(得分:2)
您可以使用Containable行为轻松完成此任务。
添加:
var $actsAs = array('Containable');
然后在您的控制器中,您可以在查找中添加“包含”选项(“全部”):
$this->Fund->find('all', array( 'contain' => array( 'Price' => array( 'limit' => 15, 'order' => 'Price.date DESC') )));
答案 1 :(得分:0)
据我所知,您不希望在模型中静态设置限制。如果您希望使用hasMany关联,除了以某种方式更改该限制之外,我确实没有任何其他方式。
以下是动态更改它的几种方法:
#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));
有关详情,请查看蛋糕文档。