如何使用 LIKE 关键字制作自定义 orderBy 或 DB::raw(FIELD()) 并在 laravel 查询构建器中传递变量

How to make custom orderBy or DB::raw(FIELD()) with LIKE keyword and passing variable in laravel query builder

我有一个非常简单的解决方案,但我不喜欢它。那么,我该怎么办?

我的数据库是

--------------------------------------
id   name   view       created_at
--------------------------------------
1   one     9      2021-01-13 12:34:22
2   two     8      2021-01-15 10:23:02
3   three   23     2021-01-15 20:55:17
4   forth   15     2021-01-16 12:34:22
5   fifth   0      2021-01-19 10:37:02

我想像这样排序和获取我的数据--

--------------------------------------
id   name   view       created_at
--------------------------------------
5   fifth   0      2021-01-19 10:37:02
3   three   23     2021-01-15 20:55:17
4   forth   15     2021-01-16 12:34:22
1   one     9     2021-01-13 12:34:22
2   two     8     2021-01-15 10:23:02

我的解决方案是

        $today = '2021-01-19';  //this date will calculate in daily. Not absolute date!

        $firstarray=Product::where('created_at','LIKE',$today.'%')->get();
        $secondarray=Product::orderBy('viewer', 'DESC')->get();
        $data = array_merge($firstarray,$secondarray);
        return $data;

实际,我想把我的代码写成这样

    $today = '2021-01-19';  //this date will calculate in daily. Not absolute date!
    $data = Product::orderBy(DB::raw('FIELD(created_at, LIKE $today."%")'),'DESC')
            ->orderBy('view','desc')->get();
    return $data;

如何获得解决我的问题的强大代码?

对不起我的英语水平
谢谢大家

你的问题不清楚!如果是我理解的方式,那就是解决方案。

$data = Product::whereDate('created_at', now())->orderBy('view','desc')->get();

我想您首先需要今天的记录,然后是按视图排序的其余记录。所以在这种情况下,您可以将结果排序为

Product::orderByRaw("date_format(created_at ,'%Y-%m-%d') = ? desc, view desc", [$today])
         ->get();

DEMO