【问题标题】:Simple query laravel 4 table and pivot table output简单查询 laravel 4 表和数据透视表输出
【发布时间】:2014-06-30 09:42:35
【问题描述】:

我认为这应该很简单,但由于某种原因它不是。

我有桌子

student 
|id|name|...etc

school
|id|name|....etc

school_student
|id|school_id|student_id

学生模型

public function schools()
{
    return $this->belongsToMany('School');
}

学校模型

public function students(){
    return $this->belongsToMany('Student');
}

例如,我只想输出属于 school_id=1 的学生。

换句话说:

    SELECT * FROM students LEFT JOIN school_student ON student.id=school_student.student_id WHERE school_id='1'

使用 Laravel 4.1 。我对 Laravel 还很陌生,也许我对此有一些心理障碍,但还没有找到可行的解决方案。

我尝试了几种方法,但都错了。没有school_id搜索的基本是:

      $students = Student::with('schools')->get();

帮助表示赞赏。

【问题讨论】:

  • 你的模型叫什么?
  • 我有更新问题要显示

标签: database laravel pivot eloquent


【解决方案1】:

根据您的需要有几种方法:

使用 ORM 关系:

// 1st query to fetch school, 2nd query to fecth the students
$school = School::find($shoolId);
$school->students; // Collection of related students

// 1 query with joins
Student::whereHas('school', function ($q) use ($schoolId) {
   $q->where('schools.id', $schoolId);
})->get();

使用手动连接:

// 1 query with join
Student::join('school_student as ss', function ($q) use ($schoolId) {
   $q->on('ss.student_id', '=', 'students.id')
     ->where('ss.school_id', '=', $schoolId);
})->get();

回答您的一个 cmets:findget 不同,第一个将返回单个模型或 null,后者将始终返回集合。

【讨论】:

    【解决方案2】:

    你可能有一个 School 模型,它应该有这样的方法......

    public function students(){
        return $this->belongsToMany('Student');
    }
    

    那你就可以了

    $school = School::with('students')->find($id);
    var_dump($school->students());
    

    【讨论】:

    • 视图输出为空。我再次检查了表格,有一个 school_student 记录 id=1,student_id=7,school_id=1 以及学生记录 id=7 和学校记录 id=1
    • 这也会通过所有用户表限制等...[{"query":"select * from users where id = ? limit 1","bindings":[" 25"],"time":0.69},{"query":"select * from throttle where user_id = ? limit 1"....
    • 虽然我仍然担心这似乎会遇到很多查询。
    【解决方案3】:

    看看http://laravel.com/docs/eloquent#eager-loading,“Eager Load Constraints”部分告诉你你需要什么

    这里是你的情况的一个例子

     $students = Student::with('schools', function($query){
              $query->where('school_id', '=', 1);
     })->get();
    

    【讨论】:

    • 我确实尝试过使用数组,但没有成功。你的给出了这个错误:explode() 期望参数 2 是字符串,给定对象
    • 你在哪里使用了数组?在哪里('school_id', '=', ARRAY)?
    • 对于您的,我完全按照发布的方式进行操作,但没有成功。我之前试过这个 $users = $students = Student::with(array('school' => function($query) {$query->where('school_id', '=', '1') ; }))->get(); 根据 laravel 文档
    猜你喜欢
    • 2015-08-06
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多