1

尝试将来自 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"))
            );
4

0 回答 0