0

結合テーブルを自動的に更新/削除したい。これを行うための回避策として、saveAll() の前に deleteAll() を実行しています。

フォームを送信すると、レイアウト モデルとコンポーネント モデルは正しく更新されますが、レイアウト コンポーネント モデル (結合テーブル) は新しいデータを挿入しますが (これが必要です)、参照データを削除しません。

レイアウト モデル:

class Layout extends AppModel {
    var $name = 'Layout';

    var $hasMany = array(
        'LayoutComponentOrder' => array(
            'className' => 'LayoutComponentOrder',
            'foreignKey' => 'layout_id',
            'dependent' => false,
            'order' => 'LayoutComponentOrder.sort_id ASC',
        ),
        'ComponentVideo' => array(
            'className' => 'ComponentVideo',
            'foreignKey' => 'layout_id',
            'dependent' => false,
        ),
);}

コンポーネント モデル:

class ComponentVideo extends AppModel {
    var $name = 'ComponentVideo';
    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $hasMany = array(
        'LayoutComponentOrder' => array(
            'className' => 'LayoutComponentOrder',
            'foreignKey' => 'layout_component_id',
            'dependent' => false,
        ),
    );

    var $belongsTo = array(
        'Layout' => array(
            'className'    => 'Layout',
            'foreignKey'    => 'layout_id'
        ),
    );
};

レイアウト コンポーネント モデル (結合テーブル):

class LayoutComponentOrder extends AppModel {
    var $name = 'LayoutComponentOrder';
    var $uses = 'layout_component_orders'; 

    //The Associations below have been created with all possible keys, those that are not needed can be removed

    var $belongsTo = array(
            'Layout' => array(
                'className'    => 'Layout',
                'foreignKey'    => 'layout_id'
            ),
            'ComponentVideo' => array(
                'className'    => 'ComponentVideo',
                'foreignKey'    => 'layout_component_id'
            )
        );
}

レイアウト コントローラー:

// deleting the data manually
$this->LayoutComponentOrder->deleteAll(array('LayoutComponentOrder.layout_id' => $layout_id));
// this one inserts into the tables including the join table        
$this->Layout->id = $layout_id;
if ($this->Layout->saveAll($this->data)) {
   $this->Session->setFlash(__('The layout has been saved', true));
}

結合を自動的に削除するにはどうすればよいですか? これはCakePHPで可能ですか?

4

2 に答える 2

1

残念ながら、これはhasMany関係のためのCakePHPのsaveAllには組み込まれていません。このページが同じことの解決策を探しているのを見つけたので、そうだったらいいのにと思います。

ただし、HABTM関係が組み込まれているようです。

saveAll()に無関係なオブジェクトを削除させる方法はありますか?を参照してください。また、saveAllは関連するレコードも削除するべきではありませんか?)

独自のソリューションを実装する必要があります(フォームが検証される場合、saveAllの前にdeleteAllを実行する私のクイックソリューション。ただし、フォームの検証に関係のないエラーがあると、既存の関連アイテムが失われるため、これは理想的ではありません)。

于 2011-04-14T23:38:09.700 に答える