Laravel:where 和 whereHas 之间的区别

cho*_*on4 1 laravel

where() 和 whereHas() 这两个方法有什么区别?它们在 Laravel 文档中似乎非常相似。

Joe*_*inz 6

该方法的where()行为类似于常规 SQLWHERE查询部分。

该方法has()使用外键关系来返回包含其他内容的内容。例如,Student::has('classes')->get();将返回所有上课的学生。

该方法whereHas()与常规方法类似has(),但它允许您对搜索施加限制。与 不同的是where(),这是在子表而不是父表上完成的。这是一个例子:

$students = Student::where('name', 'Pingu')         // constrains the students table
    ->whereHas('classes', function($query) {
        $query->where('name', 'like', '%physics%'); // constrains the classes table
    })->get();
Run Code Online (Sandbox Code Playgroud)

在这个高度现实的示例中,您希望所有名为 Pingu 的学生都在上物理课。