php - CakePHP 2.x 使用 HABTM 连接表中的数据检索/查询

标签 php mysql cakephp cakephp-2.0

我有 2 个通过 HABTM 关系连接的表。 投资组合 Assets 。连接表是portfolios_assets

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

所以,在我的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 through 模型: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' 
    )
));

关于php - CakePHP 2.x 使用 HABTM 连接表中的数据检索/查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214643/

相关文章:

php - 如何使用 volley api 将 android 应用程序连接到本地服务器

php - 从表中选择多行并在按钮单击上应用函数

php - 在 cakephp 中显示带有法语口音的数据

mysql - 获取用户发布的帖子数?

mysql - 使用 glassfish 的数据库连接的持久性异常

php - 将列类型从 json 更改为另一种

php - CakePHP 元素错误处理问题

php - 获取事件菜单-URL

php - 如何通过AJAX更改变量?

c# - 相当于PHP在C#中的include