繁体   English   中英

CakePHP 2.x使用HABTM联接表中的数据进行检索/查询

[英]CakePHP 2.x retrieve/query using data in HABTM join table

我有2个表通过HABTM关系连接。 portfoliosassets 联接表是portfolios_assets

我希望联接表中有一个额外的字段rebalance_date ,以便可以查询给定日期的投资组合中的资产。 我将如何构造find以便确定最近的日期并仅返回该日期的资产。

因此,在我的Portfolio模型中,我可能有:

$params = array(
  'conditions' => array(
    'Portfolio.id' => 5,
    '?.rebalance_date' => '2013-11-01' //no model name for this field as it's in the join table
  ),
  'order' => array(...)
 );
$result = $this->find('all', $params);

在上面的示例中,我只是键入了一个日期。 我不确定如何在不编写Cake原始查询的情况下检索最新日期。 (我可以SELECT rebalance_date FROM portfolios_assets ORDER BY rebalance_date DESC LIMIT 1;但这不遵循Cake的惯例)

您需要使用hasMany通过模型: http : //book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany-through-the-join-model

您将需要创建另一个模型,例如PortfolioAssests,并且该表将需要是Portfolio_assets而不是Portfolios_assets。

然后,您应该可以使用:

$assets = $this->Assets->find('all', array(
    'conditions' => array(
        'Portfolio.id' => 5,
        'PortfolioAsset.rebalance_date' => '2013-11-01' 
    )
));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM