【问题标题】:Using Eloquent ORM in Laravel to perform search of database using LIKE在 Laravel 中使用 Eloquent ORM 使用 LIKE 执行数据库搜索
【发布时间】:2012-11-03 10:02:35
【问题描述】:

我想使用 Eloquent 的主动记录构建来构建搜索查询,但它将是一个 LIKE 搜索。我找到了User::find($term)User::find(1),但这并没有生成类似的声明。我不是在寻找直接的答案,但如果有人至少能给我一个方向,那就太好了!

【问题讨论】:

  • laravel.com/docs/database/eloquent .. 你可以使用文档很清楚。
  • 我看过这个页面我只是没有看到任何关于使用通配符搜索的内容。我也不想在 foreach 循环中设置正则表达式,因为有数十万行
  • $email = DB::table('users')->where('id', '=', 1)->only('email');
  • 在文档中被称为fluent query builder。
  • 如果我可以将答案和您的评论标记为答案,我会的。感谢您让我朝着正确的方向前进

标签: orm laravel eloquent sql-like


【解决方案1】:

如果你像我一样不喜欢双引号,单引号对你有用:

$value = Input::get('q');
$books = Book::where('name', 'LIKE', '%' . $value . '%')->limit(25)->get();

return view('pages/search/index', compact('books'));

【讨论】:

    【解决方案2】:

    使用双引号代替单引号,例如:

    where('customer.name', 'LIKE', "%$findcustomer%")
    

    下面是我的代码:

    public function searchCustomer($findcustomer)
    {
        $customer = DB::table('customer')
                      ->where('customer.name', 'LIKE', "%$findcustomer%")
                      ->orWhere('customer.phone', 'LIKE', "%$findcustomer%")
                      ->get();
    
        return View::make("your view here");
    }
    

    【讨论】:

      【解决方案3】:

      如果需要频繁使用LIKE,可以稍微简化一下问题。可以在继承 Eloquent ORM 的模型中创建类似 () 的自定义方法:

      public  function scopeLike($query, $field, $value){
              return $query->where($field, 'LIKE', "%$value%");
      }
      

      那么你可以这样使用这个方法:

      User::like('name', 'Tomas')->get();
      

      【讨论】:

      • 这是更“Laravel”的做法。它更简洁,允许您在一个地方调整范围,而不必四处调整每个->where()
      • 真的很喜欢这个答案。这使得模型及其用法非常优雅,这就是 laravel 的意义所在。
      【解决方案4】:

      仅供参考,运算符列表(包含 like 和所有其他运算符)在代码中:

      /vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
      
      protected $operators = array(
          '=', '<', '>', '<=', '>=', '<>', '!=',
          'like', 'not like', 'between', 'ilike',
          '&', '|', '^', '<<', '>>',
          'rlike', 'regexp', 'not regexp',
      );
      

      免责声明:

      乔尔·拉森的回答是正确的。得到了我的支持。

      我希望这个答案能够更清楚地说明通过 Eloquent ORM 提供的内容(将人们直接指向正确的方向)。虽然文档链接会更好,但该链接已被证明是难以捉摸的。

      【讨论】:

        【解决方案5】:

        您可以使用 LIKE 和以下语法进行数据库查找:

        Model::where('column', 'LIKE', '%value%')->get();
        

        【讨论】:

        • 效率不高,抛出“致命错误:达到'100'的最大函数嵌套级别,正在中止!在...”
        • @gsk 我认为您加入(使用 with() 方法),然后您可以像往常一样搜索该列。语法可能类似于table.field
        猜你喜欢
        • 1970-01-01
        • 2019-03-31
        • 2019-12-13
        • 2014-09-08
        • 2015-06-26
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 1970-01-01
        相关资源
        最近更新 更多