保存相关模型数据(3级)

时间:2012-08-21 16:27:21

标签: cakephp

真的很难将模型信息保存在几个级别。

首先,我有一个费用报销 - 有很多费用(费用属于费用报销)。

支出HABTM ExpenseCode。 (这些都是火车票价,汽油费等)。

所以,我有一个新的费用页面 - (ExpenseClaimsController / add)。

这种看起来有点像电子表格,它允许您输入多行(每行都是费用)。在每一行上都有一个下拉列表来选择expenseCode。问题是expenseCode没有写入连接表(expenses_expense_codes)。

如果我添加一个单一的费用,通过未使用的即将被删除的expenseController / add它工作正常,所以问题是保存了相关的模型,模型。无法弄清楚如何执行此操作,因为expenseCode与expenseClaim模型没有直接关系,因此在我执行ExpenseClaimsController / add时不会保存。

希望有意义......

继承我的ExpenseClaimsController代码:

public function add() {
    if ($this->request->is('post')) {

        //debug($this->request->data);

        // Test
        $this->loadModel('ExpenseCode');

        // Create the claim and the expenses
        $this->ExpenseClaim->create();
        $this->ExpenseClaim->Expense->create();

        // Set the user ID
        $this->request->data['ExpenseClaim']['user_id'] = $this->Auth->user('id');

        // Set the claim status based on which submit btn was pressed
        if ($this->request->data['submit'] == 'Submit') {

            $this->request->data['ExpenseClaim']['claim_status_id'] = '2';


        } else {
            $this->request->data['ExpenseClaim']['claim_status_id'] = '1';
        }

        // Set the claim status
        $now = date('Y-m-d H:i:s');
        $this->request->data['ExpenseClaim']['date_submitted'] = $now;

        // Save both expenses and the expense claim         
        if ($this->ExpenseClaim->saveAll($this->request->data)) {
            $this->Session->setFlash('The expense claim has been saved', 'flash_success');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('The expense claim could not be saved. Please, try again.', 'flash_failure');
        }
    }

    $users = $this->ExpenseClaim->User->find('list');
    $claimStatuses = $this->ExpenseClaim->ClaimStatus->find('list');
    $expenseCodes = $this->ExpenseClaim->Expense->ExpenseCode->find('list');
    $mileageRate = $this->Auth->user('mileage_rate');
    $this->set(compact('users', 'claimStatuses', 'expenseCodes', 'mileageRate'));

    // Set errors for top of page
    $this->set('errors', $this->ExpenseClaim->validationErrors);

}

有人能指出我正确的方向吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

管理追踪问题,我不得不在ExpenseClaim中重命名字段添加到

$this->Form->input('Expense.0.ExpenseCode.ExpenseCode');

然后解决了这个问题。

希望这会对某人有所帮助。