php - Laravel 5 中的 AND 语句 Eloquent

标签 php mysql laravel laravel-5

我该怎么做,比如从“table”中获取“student_staff”等于“student”的“AND”,其中“department”等于“all”或“department”等于“department1”?任何帮助、想法、线索、建议、建议?

到目前为止,我已经尝试过

$notifications = notification::where('student_staff', '=', 'student')
    ->where('department', '=', 'all')
    ->orWhere('department', '=', 'department1')->get();

最佳答案

要回答您评论中的问题,没有什么可以扩展的。默认值已经是“和”。例如,让我们看一下您写的内容:

select from "table" where "name" is equal to "jason" AND where "age" is equal to "16"

默认的 where 子句已经做了您想要的。

Model::where('name', '=', 'jason')
     ->where('age', '=', 16)
     ->get();

这变成了类似于 select * from `TABLE` where `name` = jason and `age` = 16 的内容。

如果您查看 Eloquent /查询构建器中的 where 方法,您将看到:

public function where($column, $operator = null, $value = null, $boolean = 'and')

从第4个参数可以看出,默认已经是'and'了。在相关说明中,如果需要,您可以覆盖它并放置“或”。

Model::where('name', '=', 'jason')
     ->where('age', '=', 16, 'or')
     ->get();

不过,还有一个 orWhere 方法可以为您做到这一点。

Model::where('name', '=', 'jason')
     ->orWhere('age', '=', 16)
     ->get();

这会变成这样:

从 `TABLE` 中选择 *,其中 `name` = jason 或 `age` = 16

编辑:刚注意到您编辑了问题。

"table" where "student_staff" is equal to "student" 'AND' where "department" is equal to "all" or "department" is equal to "department1

我想你想要的实际上是这样的:“student_staff”等于“student”'AND'(其中“department”等于“all”或“department”等于“department1”)

这称为参数分组。此处的文档:http://laravel.com/docs/5.1/queries#advanced-where-clauses

要实现这个语句,应该是这样的:

$models = Model::where('student_staff', '=', 'student')
                ->where(function($query) {
                    $query->where('department', '=', 'all')
                          ->orWhere('department', '=', 'department1');
                })->get();

关于php - Laravel 5 中的 AND 语句 Eloquent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816591/

相关文章:

php - 如何使用 FluentPDO 连接列?

php - 如何使用 xampp 将 PHP 5.4 降级到 5.1.6。

php - '1' 数字出现在 wordpress 网站的侧边栏下

mysql - 使用索引优化 mySQL 数据库

PHPUnit Laravel InvalidArgumentException : Unable to locate factory with name [default] [App\User]

laravel - Chrome 使用了错误的本地 IP 地址

php - Laravel 中如何以及在何处应用 XSS 保护?

php - DOM结构,通过属性名/值获取元素

java - Hibernate Criteria - 日期比较未返回正确结果

sql - 3 表计数查询mysql