使用Find可以使用基于相关模型的条件返回值


Using Find to return values using a condition based on a related model

我有一个公司模型,它与MonthlyReturn模式相关。一家公司可以有许多MonthlyReturns。我正在尝试获得一个所有公司的数组,这些公司在指定的月份都有月度回报。

我使用的代码如下:

$this->Company->find('all', array('contain' => array(
    'MonthlyReturn' => array(
        'conditions' => array('MonthlyReturn.month' => "2012-01-01")
    )
)));

公司模式:

public $hasMany = array(
        'Employee' => array(
            'className' => 'Employee',
            'foreignKey' => 'company_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        ),
        'MonthlyReturn' => array(
            'className' => 'MonthlyReturn',
            'foreignKey' => 'company_id',
            'dependent' => false,
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );
    public $hasOne = 'Umuser';
}

此代码返回的是所有公司,而不是当月返回的公司。"MonthlyReturn.month"字段将始终采用上述格式,即年份和月份将发生变化,但始终为月份的第一个。

如有任何建议,我们将不胜感激。

您的代码说,您要求一个特定的日期,而不是一个月。

试试这个:

$this->Company->find('all', array('contain' => array(
'MonthlyReturn' => array(
    'conditions' => array('MonthlyReturn.month LIKE' => "2012-01%")
))));

我不确定是否有更好的方法,但可以通过以下两个调用来实现:

$company_ids = $this->MonthlyReturn->query("SELECT DISTINCT company_id FROM monthy_returns WHERE month = '2012-01-01';")
$this->Company->find('all', array(
    'conditions' => array('Company.id' => $company_ids[0]),
    'contain' => array('MonthlyReturn' => array(
        'conditions' => array('MonthlyReturn.month' => "2012-01-01")
    )
)));

这就是想法,但可能需要进行一些调试