単一のフォームとコントローラー アクションを使用して、3 つの異なるモデルのレコードを作成しようとしているようです。これを行うための簡単な方法を次に示します。これで、少なくとも開始することができます。
まず、エンティティ、人、および組織モデルをアプリ/モデルに作成します。
次に、次のアクションを含むエンティティ コントローラーを作成します。
public function add() {
$entity = Entities::create();
if($this->request->data && $entity->save($this->request->data)) {
echo 'Success!';
exit;
}
return compact('entity');
}
次に、/app/views/entities/add.html.php を作成します。
<?=$this->form->create($entity); ?>
<?=$this->form->label('name', 'Entity Name');?>
<?=$this->form->text('name');?>
<?=$this->form->label('person_data[name]', 'Person Name');?>
<?=$this->form->text('person_data[name]');?>
<?=$this->form->label('organization_data[title]', 'Organization Title');?>
<?=$this->form->text('organization_data[title]');?>
<?=$this->form->submit('Save');?>
<?=$this->form->end(); ?>
最後に、関係を記述し、app/models/Entities.php にフィルターを追加して、データが保存されるときに個人と組織を保存します。
<?php
namespace app\models;
use \app\models\People;
use \app\models\Organizations;
class Entities extends \lithium\data\Model {
public $belongsTo = array(
'Organizations' => array(
'class' => '\app\models\Organizations',
'key' => 'organization_id',
),
'People' => array(
'class' => '\app\models\People',
'key' => 'person_id',
),
);
public static function __init() {
parent::__init();
static::applyFilter('save', function($self, $params, $chain) {
// If data is passed to the save function, set it in the record
if ($params['data']) {
$params['entity']->set($params['data']);
$params['data'] = array();
}
$record = $params['entity'];
if(isset($record->person_data)) {
$person = People::create($record->person_data);
if($person->save()) {
$record->person_id = $person->id;
}
}
if(isset($record->organization_data)) {
$org = Organizations::create($record->organization_data);
if($org->save()) {
$record->organization_id = $org->id;
}
}
$params['entity'] = $record;
return $chain->next($self, $params, $chain);
});
}
}
?>
あなたがやろうとしていることについてあまりにも多くの仮定をした場合は、コメントを残してください。それに応じてコードを調整します. お役に立てれば!