尝试从关联表中的2个模型中保存数据,并从一个模型中的列值计算出额外数据。
订阅模式:
class Subscription extends AppModel {
public $hasAndBelongsToMany = array('User');
}
用户模型:
class User extends AppModel {
public $hasAndBelongsToMany = array('Subscription','Role');
}
加入表subscriptions_users。
这是如何在用户控制器中保存帖子 - >注册方法
if($this->User->save($this->request->data))
{
// Add row to subscriptions_users
$this->Subscription->User->create();
// Format the request data for associated table subscriptions_users
$data = $this->Subscription->handle_linked_subscription_request_data($this->request->data);
// Save data to subscriptions_users
$this->Subscription->User->saveAll($data);
// Proceed to confirm
$this->confirm($subdata_userdata);
}
订阅模型中的函数handle_linked_subscription_request_data:
public function handle_linked_subscription_request_data($data)
{
// Set array for data -> subscriptions_users
$linked_data = array();
if(isset($data) && !empty($data))
{
// Get subscriptiondata to be used in calculations valid_until, terminate_at ...
$this_subscription = $this->findById($data['User']['register_subscription_id']);
if(isset($this_subscription) && !empty($this_subscription))
{
$linked_data['Subscription']['id'] = $data['User']['register_subscription_id'];
$linked_data['User']['id'] = $data['User']['id'];
// Add number of months from current date to binding ends
$linked_data['valid_until'] = date('Y-m-d', strtotime("+1 month"));
$linked_data['activated'] = date('Y-m-d');
$linked_data['binding_to'] = date('Y-m-d', strtotime("+" . (int)$this_subscription['Subscription']['binding_months'] . " months"));
}
else
{
return false;
}
}
else
{
return false;
}
unset($data);
return $linked_data;
}
Id,user_id和subscription_id有效并插入到subscription_users"链接表" 但额外的数据:
$linked_data['valid_until'] = date('Y-m-d', strtotime("+1 month"));
$linked_data['activated'] = date('Y-m-d');
$linked_data['binding_to'] = date('Y-m-d', strtotime("+" . (int)$this_subscription['Subscription']['binding_months'] . " months"));
只是不插入,我已尝试通过更改数组索引的不同方式插入它。
如何能更好地制作这个可怕的解决方案的想法将非常感激:)
修改 通过像这样格式化数组来解决它,但仍然很难看。
$linked_data['Subscription']['User'] = array(
'subscription_id' => $data['User']['register_subscription_id'],
'user_id' => $data['User']['id'],
'valid_until' => date('Y-m-d', strtotime("+1 month")),
'activated' => date('Y-m-d'),
'binding_to' => date('Y-m-d', strtotime("+" . (int)$this_subscription['Subscription']['binding_months'] . " months"))
);