php activerecord 多对多

标签 php phpactiverecord

我有三个模型:

// 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_idcourse_id.

关于php activerecord 多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15309095/

相关文章:

PHP ActiveRecord 通过 Has_Many 关联创建子模型

mysql - 将 SQL 查询转换为 PHP Activerecord

php - nginx 和 php5-fpm 对 Laravel 应用程序的响应非常慢

php - 使用 PhpActiveRecord 检查 NULL 值

PHP 事件记录 : Multiple has many associations

php - mysql 无法在 xampp 上运行

PHPActiveRecord 编码问题

php - Laravel 将空值插入表单并将空值插入数据库

PHP - 如何获取数组值中的字符数?

PHP 环境变量转移到子进程中