2017-07-05 13 views
0

私は多少の関係で2つのモデルを持っています - 講師と生徒を例に挙げましょう。私が講師に学生を追加したいときPhalconに多対多の関係を追加する

class Lecturer 
{ 
    public function initialize() 
    { 
     $this->hasMany('studentId', 'Model\Entity\LecturerStudent', 'studentId', ['alias' => 'LecturerStudent']); 
     $this->hasManyToMany(
      'lecturerId', 
      'Model\Entity\LecturerStudent', 
      'lecturerId', 
      'studentId', 
      'Model\Entity\Student', 
      'studentId', 
      ['alias' => 'Students'] 
     ); 
    } 
} 

class LecturerStudent 
{ 
    public function initialize() 
    { 
     $this->belongsTo('studentId', 'Model\Entity\Student', 'studentId', ['alias' => 'Student']); 
     $this->belongsTo('lecturerId', 'Model\Entity\Lecturer', 'lecturerId', ['alias' => 'Lecturer']); 
    } 
} 

class Student 
{ 
    public function initialize() 
    { 
     $this->hasMany('lecturerId', 'Model\Entity\LecturerStudent', 'lecturerId', ['alias' => 'LecturerStudent']); 
    } 
} 

は今、私がする必要があるすべては、次のとおりです。私が期待する

$lecturerA = new Lecturer(); 
$studentA = new Student(); 
$studentB = new Student(); 
$lecturerA->Students = [$studentA, $studentB]; 
$lecturerA->save(); 

このすべての作品として。

私のアプリケーションでは、1つのトランザクションで多数のレコードをインポートするときに問題が発生し、関係に2番目の配列を追加する必要があります。だから例の

:この場合

$lecturerA = new Lecturer(); 
$studentA = new Student(); 
$studentB = new Student(); 
$lecturerA->Students = [$studentA, $studentB]; 

... other code doing other things ... 

$studentC = new Student(); 
$studentD = new Student(); 
$lecturerA->Students = [$studentC, $studentD]; 

... more code ... 

$lecturerA->save(); 

は、唯一の項目(複数可)が保存されStudentsと第二の割り当てに加えました。最初の割り当ての項目は失われます。だから私の例ではstudentCstudentDだけがデータベースに書き込まれます。

これを行う正しい方法はありますか?以前の多対多配列に追加するにはPhalconで行いますか?私は、インポートを実行しているクラス内でこれを行う代わりの(厄介な)方法を持っていますが、正しい方法があれば、それを使用する方が好きです。

答えて

0

2番目の割り当てが$lectureA->Studentsを上書きするため、生徒オブジェクトを一時的な配列に保存する必要があります。

$lecturerA = new Lecturer(); 
$studentA = new Student(); 
$studentB = new Student(); 
$tmpStudents = [$studentA, $studentB]; 

... other code doing other things ... 

$studentC = new Student(); 
$studentD = new Student(); 
$tmpStudents = $tmpStudents + [$studentC, $studentD]; 
$lecturerA->Students = $tmpStudents; 

... more code ... 

$lecturerA->save(); 

またはあなたが学生を設定した後、あなたが$lecturerA->save()メソッドを呼び出すことができますが、あなたがsave()を呼び出すたびに、INSERTUPDATEクエリがRDBMSに行われなければならないので、コースを外れ、これは高いネットワークトラフィックが発生しますrelationship.But。

$lecturerA = new Lecturer(); 
$studentA = new Student(); 
$studentB = new Student(); 
$lecturerA->Students = [$studentA, $studentB]; 
$lecturerA->save(); 

... other code doing other things ... 

$studentC = new Student(); 
$studentD = new Student(); 
$lecturerA->Students = [$studentC, $studentD]; 

... more code ... 

$lecturerA->save();