php - 如何在 Eloquent 中将 "or"与多个 "where"一起使用?

标签 php mysql laravel eloquent

如何在 Eloquent 中实现此功能?

select * from product where name like '%value%' and (product_type = product_type_param or product_type_param = 0);

如果提供 product_type_param 值为 0,它将选择所有类型的产品,当然还要考虑到名称也匹配。

我当前的代码:

$result = Product::where( [  ['name', 'like', '%' . 
$searchAttributes['name'] . '%'],
    ['product_type', '=', $searchAttributes['product_type']]]
     )->get();

这个想法是这样的(请原谅这个例子,它只表明了我的意图):

 ['product_type', '=', $searchAttributes['product_type']] or [$searchAttributes['product_type'] == 0]]

我应该执行原始查询吗?

最佳答案

您可以使用闭包函数来确定查询范围

Product::where('name', 'like', '%' . $searchAttributes['name'] . '%')
        ->where(function($q) use ($searchAttributes) {
             $q->where('product_type', $searchAttributes['product_type'])
               ->orWhere('product_type_param', 0);
        })->get();

关于php - 如何在 Eloquent 中将 "or"与多个 "where"一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153697/

相关文章:

javascript - 从数据库中获取数据并将其放入选择列表中

mysql程序-运行总计

java - JPA 与同一实体的两个单向@OneToMany 关系导致重复条目

php - Laravel 4 ViewModel(带 mustache )

php - 注意 : Undefined variable: table in C:\XAMPP\htdocs\progscores. php 第 27 行

PHP 搜索功能不适用于某些产品,但适用于其他产品

php - 使用 key 从 foreach 循环创建数组

MySQL Workbench 主机不匹配

php - 拉拉维尔。如果数据库正在播种,则禁用观察者方法

jquery 语义-ui 选项卡转换