Laravel - Eloquent : Advanced Wheres

标签 laravel eloquent

我正在尝试使用 Eloquent 创建类似的东西。但是,我在使用 or 子句时遇到了麻烦。

SELECT * FROM table WHERE column1 = 1 AND column2 = 2 AND (column3 LIKE $search_term.'%' OR column4 LIKE $search_term.'%') ORDER BY column1;

这是我的:

$query = DB::table('table')
        ->where('column1', '=', 1)
        ->where('column2', '=', 2)
        ->orderBy('column1', 'asc'); 

$results = App\Table::where(function ($query) use ($search_term) {
            $query->where('column3', 'like', $search_term.'%');
        })->orwhere(function ($query) use ($search_term) {
            $query->where('column4', 'like', $search_term.'%');
        });

最佳答案

您的查询应如下所示:

$query = DB::table('table')
    ->where('column1', 1)
    ->where('column2', 2)
    ->where(function ($q) use ($search_term) {
        $q->where('column3', 'like', $search_term.'%')
          ->orWhere('column4', 'like', $search_term.'%');
    })
    ->orderBy('column1', 'asc')
    ->get(); 

关于Laravel - Eloquent : Advanced Wheres,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41463262/

相关文章:

php - sizeof() : Parameter must be an array or an object that implements Countable

mysql - 从 Laravel 5.1 升级到 Laravel 5.8 后,whereHas() 速度变慢

php - 急切加载模型中的附加属性

php - 在 composer 安装期间运行 Gulp 任务

php - Laravel - 模型类,覆盖主要方法

laravel - 从 Laravel 中的 Button 或 URL 运行函数

php - 如何在 laravel eloquent 上添加括号? (拉拉维尔 5.3)

mysql - 在 Laravel 5.4 中复制一条记录及其后代

php - 将 Laravel 5 Eloquent 模型移动到它自己的目录中

php - 如何使用相关 id 在 laravel 中更新