Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel在一个集合/阵列中获取所有相关模型_Php_Laravel_Laravel 4_Orm_Eloquent - Fatal编程技术网

Php Laravel在一个集合/阵列中获取所有相关模型

Php Laravel在一个集合/阵列中获取所有相关模型,php,laravel,laravel-4,orm,eloquent,Php,Laravel,Laravel 4,Orm,Eloquent,Laravel 4 是否有任何简单的方法可以在一个集合中获得所有相关的模型(仅限于雄辩) 例如,我想得到所有的学生,这与许多课程有关: 首先,我需要获得一个具有以下关系的集合: $classes = Class::with('students')->whereIn('code', ['A', 'B'])->get(); 然后我需要通过整个集合来合并学生: $allStudents = new Collection; foreach ($classes as $class) {

Laravel 4

是否有任何简单的方法可以在一个集合中获得所有相关的模型(仅限于雄辩)

例如,我想得到所有的学生,这与许多课程有关:

首先,我需要获得一个具有以下关系的集合:

$classes = Class::with('students')->whereIn('code', ['A', 'B'])->get();
然后我需要通过整个集合来合并学生:

$allStudents = new Collection;

foreach ($classes as $class) {
    $allStudents = $allStudents->merge($class->students);
}
或者,如果我只需要一个键,例如,学生的
id
,我会这样做:

$allStudentsIds = [];

foreach ($classes->fetch('students') as $studentsArray) {
    $allStudentsIds = array_merge(
        $allStudentsIds, array_pluck($studentsArray, 'id')
    );
}

是否有只获取相关模型的方法?或者,我可以通过请求
学生
模型?

基于学生的查询和加入课堂

Student::select('student.*')
->join('class_student', 'class_student.student_id', '=', 'student.id')
->join('class', 'class.id', '=', 'class_student.class_id')
->whereIn('class.id', $classes)
->get();
差不多吧


我假设这是一个多对多关系,class_student是基于student和join with class的关联表

查询

Student::select('student.*')
->join('class_student', 'class_student.student_id', '=', 'student.id')
->join('class', 'class.id', '=', 'class_student.class_id')
->whereIn('class.id', $classes)
->get();
差不多吧

我假设这是一个多对多关系,class_student是关联表