atk4でマルチテーブルの更新/削除を実現するにはどうすればよいですか?
2 に答える
関数beforeInsert、afterInsert、beforeDelete、afterDelete、beforeUpdate、afterUpdateを使用して、データベースで追加の処理を実行できます。たとえば、WebルートでATK 4.1.3の解凍されたインストールを使用すると、以下でATKHOMEと呼ばれるagiletoolkitというフォルダーが作成されます。
mysqlに3つのフィールド(id、tasktype_desc、budget_code)を持つ単純なテーブルTASKTYPEと、idとbudget_codeだけを持つ別のテーブルTASKTYPE_BUDGETを作成します。
次のように、ATKHOME / lib / Modelのテーブルに2つのモデルを作成します(モデルディレクトリが存在しない場合は、作成する必要がある場合があります)。
class Model_TaskType extends Model_Table {
public $entity_code='tasktype';
public $table_alias='ty';
function defineFields(){
parent::defineFields();
$this->newField('id')
->mandatory(true);;
$this->newField('tasktype_desc')
->mandatory(true);
$this->newField('budget_code')
->mandatory(true);
}
public function afterInsert($new_id){
$ttb=$this->add('Model_TaskTypeBudget');
$ttb->set('id',$new_id)
->set('budget_code',$this->get('budget_code'));
$ttb->insert();
return $this;
}
public function beforeUpdate(&$data){
$ttb=$this->add('Model_TaskTypeBudget')->loadData($data['id']);
$ttb->set('budget_code', $data['budget_code']);
$ttb->update();
return $this;
}
public function beforeDelete(&$data){
$ttb=$this->add('Model_TaskTypeBudget')->loadData($data['id']);
$ttb->delete();
return $this;
}
}
innoDBを使用していて外部キーがある場合は、正しい順序で挿入と削除を行う必要があります。たとえば、IDにTaskTypeBudgetからTaskTypeへの外部キーがある場合は、制約違反を防ぐためにbeforeDeleteとafterInsertを使用する必要があります。
class Model_TaskTypeBudget extends Model_Table {
public $entity_code='tasktype_budget';
public $table_alias='tyb';
function defineFields(){
parent::defineFields();
$this->newField('id')
->mandatory(true);
$this->newField('budget_code')
->mandatory(true);
}
}
そしてATKHOMEのページ/このようなページ
class page_tasktype extends Page {
function init(){
parent::init();
$p=$this;
$tt=$this->add('Model_TaskType');
$crud=$p->add('CRUD');
$crud->setModel($tt, array('id','tasktype_desc', 'budget_code'));
if($crud->grid)
$crud->grid->addPaginator(10);
}
}
開口部を含めるように注意してください<?各クラス行の前にphpタグがありますが、終了を含めないでください。>これはAjaxでエラーを引き起こす可能性があるためです。
ATKHOME / config-default.phpで、mysql接続のユーザー名とパスワードをroot/rootからmysqlデータベースのユーザーとパスワードに変更します。
$config['dsn']='mysql://atktest:atktest@localhost/atktest';
そして、ATKHOME / lib / Frontend.phpを変更して8行目のコメントを外し、すべてのページがデータベースに接続できるようにします($ this-> dbConnect();行をページに追加することもできます。
class Frontend extends ApiFrontend {
function init(){
parent::init();
$this->dbConnect(); //uncommented
同じFrontend.phpで、次の50行目を挿入して、デフォルトメニューにボタンを追加し、新しいページを追加します。
->addMenuItem('CRUD Test', 'tasktype')
次に、Webブラウザーに移動して、http:// localhost / agiletoolkitと入力し、最初のページで[CRUDTest]をクリックします。行を追加すると、TASKTYPEに行が追加され、TASKTYPE_BUDGETに同じIDとbudget_codeを持つ行が追加されます。Budget_codeを編集すると両方のテーブルに反映され、行を削除すると両方のテーブルから削除されます。
ATk4が機能を提供していることを知ったら、どれほどすっきりとシンプルになりますか?
モデル レベルで関連エンティティを追加できます。
https://stackoverflow.com/a/7466839/204819
これがオプションでない場合は、いつでも「編集」および「削除」ボタン用のカスタム ハンドラーを作成し、内部 ORM を使用して、またはモデル レベルでもアクションを実行できます。