2

Drawing には多くの Panel があり、Panel は Drawing に属しています。パネルが保存されるたびに、それが図面に追加される 3 番目のパネルかどうかを確認したいと思います。そうであれば、3 つのパネルを 1 つの新しい png ファイルにマージし、png のファイル名とパスを Drawing テーブルに保存したいと思います。

class Drawing extends AppModel {
  public $name = 'Drawing';
  public $hasMany = array(
    'Panel' => array(
        'className' => 'Panel',
        'dependent' => true,
        'fields' => array('id', 'filepath', 'filename', 'placement')
        )
  );
}

class Panel extends AppModel {
  public $name = 'Panel';
  public $belongsTo = array(
    'Drawing'=>array(
        'className'=>'Drawing',
        'foreignKey'=>'drawing_id',
        'counterCache' => true
        )
    );
}

Panel モデルで counterCache を true に設定したので、図面テーブルで panel_count を使用してパネルを追跡し、3 つのパネルがある場合に確認できます。afterSave() コールバックを使用するのが最善の方法だと思います。そうすれば、現在 3 つのパネルがあるかどうかを確認でき、ある場合は必要に応じて更新できます。(私のコントローラーは、3 つになるとユーザーが新しいパネルを追加できないようにします)。ただし、以下のコードは機能しないと思います。アプリの他の部分が機能しなくなり、afterSave() 関数を削除すると、すべてが再び機能します。描画モデル内から panel_count を確認するにはどうすればよいですか? これを行うより良い方法はありますか?

// Inside of the Drawing model... 
public function afterSave($created){
  if ($this->data[panel_count] == 3){
    // create a new image by merging the three panel images together
    // add the filename and path of the new image to the database
  }
}
4

1 に答える 1

0

機能を実行する新しいモデル メソッドを作成し、コントローラーからそのメソッドで保存します。この理由は Drawing.panel_count プロパティの変更です (Drawing レコードを更新する必要があり、これにより afterSave ループが作成されます)。

通常、データ マングリング (特に同じモデル内) のコールバックは避けます。コールバックは毎回実行され、余分なマングリングを行わずに単純に SAVE したい場合があるためです。コードの一部をメソッドから afterSave コールバックに後で移動する方が、その逆よりもはるかに簡単です。

于 2013-01-27T10:03:04.050 に答える