Hello! There are misunderstandings in ORM. I have three tables: persons, birhplace and special_signs.

persons: id | name | last_name | patronymic | birthday | sex |

birthplace: id | person_id | country | region | city ​​|

special_signs: id | person_id | signs |

The persons table is the main one. The data in the birthplace and special_signs tables may or may not be added.

Accordingly, I create three models:

//person.php class Model_Person extends ORM { protected $_table_name = 'persons'; } //birthplace.php class Model_Birthplace extends ORM { protected $_table_name = 'birthplace'; } //specialsigns.php class Model_Specialsigns extends ORM { protected $_table_name = 'special_signs'; } 

Now in the Person controller I am processing the input:

 public function action_save(){ if(isset($_POST['save_btn']))){ if(isset($_POST['person'])){ $person = Validation::factory($_POST['person']) ->rule('name','not_empty') ->rule('last_name','not_empty') ->rule('patronymic','not_empty') ->rule('birthday',array($this,'check_date'),array(':validation',':field',':value')) ->rule('sex','digit') if($person->check()){ $person_save = ORM::factory('persons'); $person_save->values(array( 'name' => HTML::entities(strip_tags($person['name'])), 'last_name' => HTML::entities(strip_tags($person['last_name'])), 'patronymic' => HTML::entities(strip_tags($person['patronymic'])), 'birthday' => $this->build_date($person['birthday']), 'sex' => (($person['sex'] == 0) ? 'famale' : 'male'), ) )->save(); //$person_save->id; } } } } 

And the question! How to save data in birthplace and special_signs? Will it be correct, after adding the data to the persons table, to write:

 //Проводим валидацию массива birthplace, если он не пуст, то добавляем данные. ORM::factory('birthplace')->values( 'person_id' => $person_save->id ...... ); //Проводим валидацию массива special_signs, если он не пуст, то добавляем данные. ORM::factory('special_signs')->values( 'person_id' => $person_save->id ...... ); 

Or for such purposes use Query_Builder? What can you advise? Thank.

    1 answer 1

    You think correctly. I would do this:

      $db = Database::instance(); try { $db->begin(); $person_save->save(); //здесь $person_save->id уже заполнен $person_save->save_birthplace($_POST); // сохраняем зависимые записи $person_save->save_specialsigns($_POST); $db->commit(); $this->request->redirect( $this->object_list_url ); } catch ( Kohana_ORM_Validation_Exception $ex ) { $view->errors = $ex->errors("models"); $db->rollback(); } 

    And add the save_birthplace () and save_specialsigns () functions to the model. If saving the linked records fails, the transaction can be rolled back.