【问题标题】:How to find data matching the search in any field of the column in laravel如何在laravel中的列的任何字段中查找与搜索匹配的数据
【发布时间】:2021-08-29 14:02:00
【问题描述】:

我正在尝试从名为 item 的表中获取数据,并且我想将包含用户搜索的搜索字符串的项目带入,例如用户搜索“活动”,因此它会从表中获取任何字段中的数据包含“活动”一词。我试图用这段代码来做,但它不起作用。

Route::get('/data', function () {
$items = Item::where('status', 'Like', 'active')->get();
dd($items); });

谁有解决办法?

【问题讨论】:

  • $items = Item::where('status', 'like', '%active%')->get();
  • 谢谢,但在这种情况下它只搜索 1 个字段,字段状态有没有办法搜索所有字段?

标签: php database laravel search eloquent


【解决方案1】:

你可以使用

$items = Item::where('status', 'like', '%active%')->get();

要搜索多个列,您可以像下面这样orwhere

 $items = Item::where('status', 'like', '%active%')
->orWhere('column2', 'like', '%active%')
->orWhere('column3', 'like', '%active%')
->get();

$columns=['col1','col2','col3'];

 $items = Item::query();
foreach($columns as $column){
$items->orWhere($column,'like','%active%')
}
$result=$items->get();

 $columns=['col1','col2','col3'];
    
     $items = Item::where(function($query)use($columns){
 foreach($columns as $column){
   $query->orWhere($column,'like','%active%')
    }
})->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-27
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多