我有这张桌子:
客户[id,姓名,姓氏,电话,文字,余额,已创建]
service_types [id,标题,价格,长度,is_subscription,已创建]
customer_service_types [id,customer_id,service_type_id,价格,已创建]
当我为客户添加新的customerServiceType
时,我想使用给定的balance
的{{1}}值来更新客户的price
。
这就是我尝试过的:
customerServiceType
:
CustomerServiceTypes/add.ctp
<fieldset>
<legend><?= __('Add Customer Service Type') ?></legend>
<?php
echo $this->Form->control('customer_id', ['options' => $customers]);
echo $this->Form->control('service_type_id', ['options' => $serviceTypes]);
echo $this->Form->control('price');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
:
Model/Entity/CustomerServiceType.php
因此,在class CustomerServiceType extends Entity
{
//On create a new CustomerServiceType then update the selected customer's balance
public function addCustomerServiceType($data = array()){
$this->create;
$this->save($data);
//update customer balance
$customer = $this->Customers->get($data['customerid']);
$this->Customer->updateAll(
array('Customer.balance' => 'Customer.balance + ' . $data['price']),
array('Customer.id' => $data['customerid'])
);
return true;
}
}
中,我像这样更改了CustomerServiceTypesController.php
:
add()
但是我得到这个错误:
在布尔值上调用成员函数addCustomerServiceType()
此通知:
未定义的属性:CustomerServiceTypesController :: $ CustomerServiceType
答案 0 :(得分:1)
由于您希望在保存数据后发生,因此我认为使用Model.afterSave
事件:https://book.cakephp.org/3.0/en/orm/table-objects.html#aftersave
$this->CustomerServiceTypes->save($customerServiceType)
CustomerServiceTypesTable.php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Event\Event;
use Cake\ORM\TableRegistry;
use ArrayObject;
use Cake\Datasource\EntityInterface;
class CustomerServiceTypesTable extends Table
{
public function afterSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
// only execute if the entity is new
// if you want this to happen on edits too, remove this clause
if ($entity->isNew()) {
// get instance of the Customers table
$customers = TableRegistry::getTableLocator()->get('Customers');
$customer = $customers->get($entity->customerid);
// do more stuff here
}
}
}