doujing6053 2013-12-02 21:59
浏览 204

Laravel + Eloquent:在一个查询中组合2个表

I am trying to perform a query with Eloquent where I can get all the courses of an user.

Users have their courses because they are in some grade. So all courses of this grade will be included.

$user->grade->courses

Now I'd like to include some courses that are not in the user's grade thanks to the pivot table : users_courses. But I don't know how to query all tables at once using Eloquent.

enter image description here

EDIT : Here is what have

class Users extends Eloquent {
    public function courses()
    {
        return $this->belongsToMany('Courses', 'users_courses', 'student_id', 'course_id');
    }

    public function grade()
    {
        return $this->belongsTo('Grades', 'grade_id');   
    }
}

class Courses extends Eloquent {
    public function grade()
    {
        return $this->belongsTo('Grades');
    }

    public function users()
    {
        return $this->belongsToMany('Users', 'users_courses', 'student_id', 'course_id');
    }
}

class Grades extends Eloquent {

    public function courses()
    {
        return $this->hasMany('Courses', 'grade_id');
    }

    public function users()
    {
        return $this->hasMany('Users', 'grade_id');
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度