简体   繁体   中英

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

I have 2 tables joined by a HABTM relationship. portfolios and assets . The join table is 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. How would I construct a find such that I can determine the most recent date and only return the assets for that date.

So, in my Portfolio model I might have:

$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. (I could do SELECT rebalance_date FROM portfolios_assets ORDER BY rebalance_date DESC LIMIT 1; but this is not following Cake's convention)

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

You would need to create another model eg PortfolioAssests and the table would need to be portfolio_assets not 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' 
    )
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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