Cakephp 2 request data and model

2019-08-29 06:48发布

问题:

I have 2 models. Order & OrderProduct

When an Order to is added, Im trying to manipulate the OrderProduct data in the beforeValidate() of the Order Model but unsuccessfully.

I've tried. (Both in Order model)

function beforeValidate() 
{
    parent::beforeValidate();
    $this->data['OrderProduct']['total'] = 1000;
    return true;
}

function beforeValidate() 
{
    parent::beforeValidate();
    CakeRequest::data('OrderProduct.total', 1000);
    return true;
}

But the OrderProduct data isnt being modified when viewed from the controller after a failed transaction (!this->saveAll()).

Could any suggest a alternative solution with out manually setting the data in the controller.

回答1:

Try $this->request->data['OrderProduct']['total'] = 1000;



回答2:

You need to call a successful save somewhere to change a record in the DB. If you do a save and it fails, then the value you are editing will be discarded.

FYI, the first one should work for setting a value in $this->data.

All you need now is a transaction that doesn't fail. i.e.

$this->save($this->data);

Also note, the call to save will need either more information such as an id, or you'll need to read a record first and then save it.