我有三个模型:
// student_id student_name
Student extends ActiveRecord\Model
{
static $has_many = array(
array('studentcourses')
);
}
// course_id course_name
Course extends ActiveRecord\Model
{
static $has_many = array(
array('students')
);
}
// course_id student_id
Studentcourse extends ActiveRecord\Model
{
static $belongs_to = array(
array('student')
);
}
因此,通过这样做,我将能够轻松地从这些表中检索数据:
$student = Student::find(1);
foreach ($student->studentcourses as $course)
{
echo $course->name;
}
但是我不想输入“studentcourses”,而是想输入 $student->courses 来获取学生参加的所有类(class),并输入 $course->students 来获取特定类(class)的学生列表。关系设置如何才能实现这一目标?
最佳答案
我认为你需要的是多对多的关系。要在 PHP-AR 中进行设置:
// student_id student_name
Class Student extends ActiveRecord\Model
{
static $has_many = array(
array('courses', 'through' => 'studentcourses'),
array('studentcourses')
);
}
// course_id course_name
Class Course extends ActiveRecord\Model
{
static $has_many = array(
array('students', 'through' => 'studentcourses'),
array('studentcourses')
);
}
// course_id student_id
Class Studentcourse extends ActiveRecord\Model
{
static $belongs_to = array(
array('student'),
array('course')
);
}
不要忘记 studentcourses 表必须包含:id(主键)、student_id 和 course_id强>.
关于php activerecord 多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309095/