代码之家  ›  专栏  ›  技术社区  ›  smzapp

如何在laravel eloquent中对结果进行优先排序

  •  3
  • smzapp  · 技术社区  · 7 年前

    我有一个4列的表。我想根据输入显示行,它应该能够根据优先级字段显示优先级。

    示例:我的表如下所示:

    ID  title          description    tags
    1   web developer  designer       front-end
    2   designer       front-end      web developer
    3   front-end      web developer  designer
    

    $input = 'web developer' // the sequence should be IDs : 1, 3, 2
    $input = 'front-end'     // output sequence result is : 3, 2, 1
    $input = 'designer'      // result sequence : 2, 1, 3
    

    $blog = DB::('blogs')
            ->where('title', 'LIKE', '%$title%')
            ->where('description', 'LIKE', '%$title%')
            ->where('tags', 'LIKE', '%$title%');
    

    但是上面的代码,似乎没有。。

    2 回复  |  直到 7 年前
        1
  •  7
  •   audiojames Tim Biegeleisen    4 年前

    我认为你想要排序结果的逻辑应该出现在 ORDER BY 条款考虑以下原始查询:

    SELECT *
    FROM yourTable
    ORDER BY
        CASE WHEN title = 'web developer'       THEN 0 ELSE 1 END,
        CASE WHEN description = 'web developer' THEN 0 ELSE 1 END,
        CASE WHEN tags = 'web developer'        THEN 0 ELSE 1 END;
    

    输出:

    Image showing ordered results

    orderByRaw :

    $orderByClause  = "CASE WHEN title = '".$input."' THEN 0 ELSE 1 END,";
    $orderByClause .= "CASE WHEN description = '".$input."' THEN 0 ELSE 1 END,";
    $orderByClause .= "CASE WHEN tags = '".$input."' THEN 0 ELSE 1 END";
    
    $blog = DB::('blogs')
            ->orderByRaw($orderByClause)
            ->get();
    

    我找不到任何关于如何参数化

    此处演示:

    Rextester

        2
  •  2
  •   Tim Biegeleisen    7 年前

    这不是一个好的解决方案,但这可能会帮助你,

    $input = 'web developer';
    
    $byTitle = DB::('blogs')
               ->where('title', 'LIKE', '%$input%')
               ->select('id');
    
    $byDescription = DB::('blogs')
                     ->where('description', 'LIKE', '%$input%')
                     ->select('id');
    
    $byTag = DB::('blogs')
             ->where('tag', 'LIKE', '%$input%')
             ->select('id');
    
    $ids = $byTitle->union($byDescription)->union($byTag)->get();
    

    如果您想通过 UNION

    SELECT ID, 1 AS priority
    FROM blogs
    WHERE title = 'web developer'
    UNION
    SELECT ID, 2
    FROM blogs
    WHERE description = 'web developer'
    UNION
    SELECT ID, 3
    FROM blogs
    WHERE tags = 'web developer'
    ORDER BY
        priority,
        ID