搜索数据表雄辩

时间:2019-05-17 01:28:50

标签: php eloquent

我有3张桌子

students
- id
- name

classes
- id
- name

student_class
- id
- student_id
- class_id
- score 

我想返回属于 class_id = 100

的学生的列表
$students = \Student::where(['class_id' => 100])->get();

这是我的学生班

use Illuminate\Database\Eloquent\Model;
class Student extends Model
{

    protected $table = 'students';

    public function store(Request $request)
    {
        $student = new Student;
        $student->save();
    }  
}

我得到的错误是:

<strong>Message:</strong> SQLSTATE[42S22]: Column not found: 1054 Unknown column 'class_id' in 'where clause' (SQL: select * from `students` where (`class_id` = 100))

更新:我可以

$students = \Class::find(100)->with(['students'])->get();

,它将以班级形式返回所有学生,但我不需要。 我需要来自学生和数据透视表(student_class)的数据,特别是de score列。

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

更新:在两个模型关系中都添加

return $this->belongsToMany('App\Class')->withPivot('score');

现在您可以在循环中执行此操作

foreach ($student->classes as $class) {
    echo $class->pivot->score;
}

答案 1 :(得分:0)

将您的学生模型更新为

public function classes(){
    return $this->belongsToMany(Class::class, 'student_class', 'student_id', 'class_id');
}

//查询

Student::whereHas('classes', function ($query) {
    $query->where('id', 100);
})->get();