Reputation: 24077
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)
Upvotes: 1
Views: 933
Reputation: 349
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'
)
));
Upvotes: 2