【发布时间】:2017-12-08 21:15:30
【问题描述】:
我在多对可能的关系中有两个模型 - 让我们以讲师和学生为例。
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 的项目。第一次分配的项目丢失。所以在我的例子中,只有studentC 和studentD 会被写入数据库。
在 Phalcon 中是否有正确的方法来执行此操作 - 添加到以前的多对多数组?在执行导入的类中,我有另一种(更混乱的)方法来执行此操作,但如果有正确的方法,我更愿意使用它。
【问题讨论】:
标签: php model many-to-many phalcon