添加项目到Phalcon多对多关系

时间:2017-07-05 09:27:59

标签: php model many-to-many 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();

这一切都符合我的期望。

当我在一个事务中导入大量记录并且我需要在关系中添加第二个数组时,问题出现在我的应用程序中。

所以在示例中:

$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中有没有正确的方法 - 添加到以前的多对多数组?在进行导入的课程中,我有另一种(杂乱的)方法可以做到这一点,但如果有正确的方法,我更喜欢使用它。

1 个答案:

答案 0 :(得分:1)

您需要将学生对象存储到临时数组,因为第二次分配将覆盖$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进行查询。

$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();