【问题标题】:CakePHP - access to associated model in beforeSaveCakePHP - 在 beforeSave 中访问关联模型
【发布时间】:2014-02-27 04:31:11
【问题描述】:

在我的应用中,报价属于产品,而产品又属于材料。由于在从 Quote 模型访问时我无法让产品模型 afterFind 数组包含材料,因此我已将 Quote 直接与材料相关联。

我现在遇到的问题是,需要根据为报价选择的产品自动保存报价的 material_id

即在 Quote 保存到数据库之前,自动从所选产品中提取 Product.material_id 的值并将其保存到 Quote.material_id 字段。

我对 cakePHP 很陌生。有谁知道如何做到这一点?

编辑:

这里有一个例子来帮助解释。在我的报价模型中,我可以拥有:

public function beforeSave($options) {
    $this->data['Quote']['material_id'] = 4;
    return true;
}

但我需要做更多这样的事情,但这是行不通的:

public function beforeSave($options) {
    $this->data['Quote']['material_id'] = $this->Product['material_id'];
    return true;
}

【问题讨论】:

    标签: cakephp cakephp-2.0


    【解决方案1】:

    我很震惊这还没有得到正确的回答......

    Oldskool 的回答是半正确的,但并不完全正确。 "$this->Quote" 的使用是不正确的,因为 beforeSave 函数本身位于 Quote 类中。我会用一个例子来解释。

    ->我们有一个模型Subscription,它属于一个SubscriptionsPlan

    -> 模型 SubscriptionsPlan hasMany 订阅

    要在 Subscription 模型的 beforeSave 函数中访问 SubscriptionsPlan 数据,您需要执行以下操作:

    public function beforeSave($options = array()){
        $options = array(
            'conditions' => array(
                'SubscriptionsPlan.subscriptions_plan_id' => $this->data[$this->alias]['subscriptions_plan_id']
            )
        );
    
        $plan = $this->SubscriptionsPlan->find('first', $options);
    
        //REST OF BEFORE SAVE CODE GOES HERE
        return true;
    }
    

    【讨论】:

      【解决方案2】:

      它应该可以通过使用 find 来代替。

      public function beforeSave($options) {
          // Assuming your Product model is associated with your Quote model
          $product = $this->Quote->Product->find('first', array(
              'conditions' => array(
                  'Product.material_id' => $this->data['Quote']['material_id']
              )
          ));
          $this->data['Quote']['material_id'] = $product['material_id'];
          return true;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多