以嵌套关系获取字段的值

时间:2014-03-04 15:30:45

标签: cakephp

我有两个关系表。 find方法非常有效,没有问题,我得到了两个表之间所需的所有字段。删除方法也可以正常工作。

但我想在删除记录之前添加验证,验证与次表的关系,如果存在关系则无法删除记录。

我的表格

  • 发票:id,company_id,number,invoice_date
  • invoice_numbers:id,company_id,number
  • 公司:id,name

我的模特

发票

class Invoice extends AppModel
{
    public $belongsTo = array(
        'Company',
        'InvoiceNumber' => array(
            'className' => 'InvoiceNumber',
            'foreignKey' => false,
            'conditions' => array(
                'InvoiceNumber.company_id = Invoice.company_id',
                'InvoiceNumber.number = Invoice.number',
            ),
            'type' => 'left',
            'fields' => array(
                'FacturaNumero.id',
            ),
        )
    );
}

InvoiceNumber

class InvoiceNumber extends AppModel
{
    public $hasOne = array(
        'Invoice' => array(
            'className' => 'Invoice',
            'foreignKey' => false,
            'conditions' => array(
                'Invoice.company_id = InvoiceNumber.company_id',
                'Invoice.number = InvoiceNumber.number',
            ),
            'type' => 'left',
            'fields' => array(
                'Invoice.invoice_date',
            ),
        )
    );
}

我的控制器(删除方法):

public function delete($id)
{
    $this->InvoiceNumber->id = $id;

    if (!$this->InvoiceNumber->exists()) {
        throw new NotFoundException('Invalid Record.');
    }

    /**
     * I want to add a validation here if field invoide_date is not null, by example
     * but this dont work, because get the first value in the invoice table.
    */  
    if (!empty($this->InvoiceNumber->Invoice->field('invoice_date')) {
        throw new NotFoundException('I Cant Delete this record.');
    } else {
        $this->InvoiceNumber->delete();
    }

}

1 个答案:

答案 0 :(得分:1)

这里的误解是你写的时候

$this->InvoiceNumber->Invoice

您只是访问通用发票模型对象而不是该特定InvoiceNumber的发票

我认为您只需要在

中更改代码
$InvoiceNumber = $this->InvoiceNumber->read();
if (!empty($InvoiceNumber['Invoice'])) {
    // ...
}

但也许这不是最好的方法:我认为更简洁的方法可能是在InvoiceNumber beforeDelete()方法中进行验证

PS:抱歉打字错误。现在应该是正确的