【问题标题】:How to do search filtering through a collection of arrays?如何通过数组集合进行搜索过滤?
【发布时间】:2019-05-21 16:52:44
【问题描述】:

我将在 laravel 5 中构建高级搜索功能。我通过过滤 negeriID、categoryID 和operasiID 等几个字段从“itemregistrations”表中查询。我需要做数组映射来计算每个项目的年龄值并放入数组中。通过使用 itemregistration 表获取值并计算年龄运行正常,但在搜索 if 语句时出现问题。它无法通过集合中的数组搜索和检索值。

   $newitem = DB::table('itemregistrations')
        ->select('itemregistrations.*')
        ->get();

    //added code to get 'age' value:
    $newitem->map(function ($detail) {

        $detail->age = \Carbon\Carbon::createFromFormat('Y',$detail->lahir_yy)->diffInYears(); 
        return $detail;
    });   


    if ($request->has('negeri_lahir')) {
        $newitem->where('NegeriID', '==', $request->negeri_lahir);
    }

    if ($request->has('kategori')) {
        $newitem->where('CategoryID', $request->kategori);
    }

    if ($request->has('pangkat')) {
        $newitem->where('OperasiID', $request->pangkat);
    }

   dd($newitem->get()); 

由于添加了数组映射的问题,将集合转换为数组值导致此错误。 它正在产生错误:

 Type error: Too few arguments to function Illuminate\Support\Collection::get(), 0 passed in C:\xampp\htdocs\

这是 dd($newitem); 集合中的数组列表

 #items: array:1123 [▼
0 => {#709 ▶}
1 => {#680 ▶}
2 => {#681 ▶}
3 => {#712 ▶}

Collection {#671 ▼
#items: array:1123 [▼
0 => {#709 ▼
  +"ItemRegistrationID": 1
  +"COID": 109064
  +"FType": ""
  +"STNo": "0"
  +"RegistrationDate": "2005-12-01"
  and more attributes...

如何开启数组列表的搜索功能?

【问题讨论】:

    标签: arrays laravel-5 advanced-search searchfiltercollection


    【解决方案1】:
    1. 首先,您不需要在查询中使用select()
    2. 使用when() 在数据库查询中进行过滤似乎更好。

    试试:

    $newitem = DB::table('itemregistrations')
        ->when(request('age'), function($query){
            $query->whereRaw('YEAR(curdate()) - lahir_yy >= ?', [request('age')]);
        })
        ->when(request('negeri_lahir'), function($query){
            $query->where('NegeriID', request('negeri_lahir'));
        })
        ->when(request('kategori'), function($query){
            $query->where('CategoryID', request('kategori'));
        })
        ->when(request('pangkat'), function($query){
            $query->where('OperasiID', request('pangkat'));
        })
        ->get();
    

    【讨论】:

    • 对不起,我需要提一下,我需要在过滤搜索之前计算年龄,因为我也需要过滤年龄
    • @joun 我更正了我的答案。你可以试试这样的。
    • 效果很好..只有年龄搜索不正确..我不确定它是否搜索计算的年龄,但结果不是根据年龄搜索..应该是年龄=40 将搜索 40 岁以上的年龄..谢谢
    • @joun 澄清一下,您需要 age=40 或 age>40?
    • 谢谢 IndianCoding,我的错误..您的代码运行良好..只是变量文本名称中的年龄错误..我刚刚注意到..这就是它没有得到过滤年龄数字的原因。但是我之前已经接受了您的回答..再次感谢..
    猜你喜欢
    • 2015-03-13
    • 2021-09-13
    • 1970-01-01
    • 2021-04-29
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    相关资源
    最近更新 更多