简体   繁体   English

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

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

I have 2 tables joined by a HABTM relationship. 我有2个表通过HABTM关系连接。 portfolios and assets . portfoliosassets The join table is portfolios_assets . 联接表是portfolios_assets

I wish to have an extra field in the join table, rebalance_date such that I can query the assets in a portfolio for a given date. 我希望联接表中有一个额外的字段rebalance_date ,以便可以查询给定日期的投资组合中的资产。 How would I construct a find such that I can determine the most recent date and only return the assets for that date. 我将如何构造find以便确定最近的日期并仅返回该日期的资产。

So, in my Portfolio model I might have: 因此,在我的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);

In the above example, I just keyed in a date. 在上面的示例中,我只是键入了一个日期。 I'm not sure how I would retrieve the latest date without writing a raw query in Cake. 我不确定如何在不编写Cake原始查询的情况下检索最新日期。 (I could do SELECT rebalance_date FROM portfolios_assets ORDER BY rebalance_date DESC LIMIT 1; but this is not following Cake's convention) (我可以SELECT rebalance_date FROM portfolios_assets ORDER BY rebalance_date DESC LIMIT 1;但这不遵循Cake的惯例)

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

You would need to create another model eg PortfolioAssests and the table would need to be portfolio_assets not portfolios_assets. 您将需要创建另一个模型,例如PortfolioAssests,并且该表将需要是Portfolio_assets而不是Portfolios_assets。

Then you should be able to use: 然后,您应该可以使用:

$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