many_many
many_many では、from_id に紐づく row を全て物理 delete してから、
配列で与えた to_id を新規に row を insert して保存する。
繰り返すと、primary id がどんどん大きくなる。
そこを気にしなければ、お手軽に save() 出来る。
(※ コードはあくまで概略でかなり手抜き)
subjects (id, name)
id |
name |
1 |
国語 |
2 |
算数 |
3 |
理科 |
4 |
社会 |
5 |
英語 |
students (id, name)
students_subjects (id, student_id, subject_id)
<?php
Model_Subject
{
$_many_many = array('students');
}
Model_Student
{
$_many_many = array('subjects');
}
$_POST['subject_ids'] = array(1,3,4);
$subject_ids = Input::post('subject_ids');
$subjects = array();
foreach ($subject_ids as $subject_id)
{
$subjects[] = Model_Subject::find($subject_id);
}
$student = Model_Student::find(3);
$student->subjects = $subjects;
$student->save();
students_subjects (id, student_id, subject_id)
id |
student_id |
subject_id |
1 |
3 |
1 |
2 |
3 |
3 |
3 |
3 |
4 |
違うデータを与えてもう一度実行
<?php
$_POST['subject_ids'] = array(4, 5);
$subject_ids = Input::post('subject_ids');
$subjects = array();
foreach ($subject_ids as $subject_id)
{
$subjects[] = Model_Subject::find($subject_id);
}
$student = Model_Student::find(3);
$student->subjects = $subjects;
$student->save();
students_subjects (id, student_id, subject_id)
id |
student_id |
subject_id |
4 |
3 |
4 |
5 |
3 |
5 |
バリデーションルール自作で、フィールド名を参照したい
<?php
public static function _validation_less_than($val, $fieldname)
{
return $val < Validation::active()->input($fieldname);
}