简体   繁体   English

在Laravel 5.2查询中将varchar转换为日期

[英]Casting varchar to date in where query Laravel 5.2

I am trying to pick a collection of data from a range using the date as the sorting column. 我正在尝试使用日期作为排序列从一个范围中选择数据集合。 But the problem is that the date in my table is saved as a varchar string. 但是问题是我表中的日期另存为varchar字符串。

NOTE: The varchar field type needs to stay as it used by some non laravel, legacy codebase, and I will disrupt service if altered to date type. 注意:varchar字段类型需要保持不变,因为某些非Laravel,旧版代码库使用了该字段,如果更改为日期类型,我将中断服务。

I have tried casting it but it doesn't work. 我已经尝试过投放它,但是它不起作用。

This is the code in the controller 这是控制器中的代码

        switch ($range) {
        case 'thisWeek':
            $start = Carbon::now()->startOfWeek()->format('d-m-y');
            $end = Carbon::now()->endOfWeek()->format('d-m-Y');     
            break;

        case 'thisMonth':
            $start = Carbon::now()->startOfMonth()->format('d-m-Y');
            $end = Carbon::now()->endOfMonth()->format('d-m-Y');
            // dd($start, $end);
            break;


        case 'last90Days':
            $start = Carbon::now()->format('d-m-Y');
            $end = Carbon::now()->subDays(90)->format('d-m-Y');

            // dd($start, $end);
            break;

        case 'last30Days':
            $start = Carbon::now()->format('d-m-Y');
            $end = Carbon::now()->subDays(30)->format('d-m-Y');
            break;


        case 'year':
            $start = Carbon::now()->format('d-m-Y');
            $end = Carbon::now()->year;
            $end = "31-12-". $end;
            break;

        // case 'all':
        //  $route = $name .".". "index";
        //  return redirect()->Route($route);

        default:
            session()->flash("alert-danger", "no range selected");
            return redirect()->back();
            break;
    }

    if($name=="activitylog"){

        // return $start . ' <br>' . $end;

        $logs = Payment::where("payDate", '<', $start)->where("payDate", ">", $end)->
                        orderBy("payDate", "DESC")->
                        paginate(20);
    }
    else{
        $logs = Payment::where("description", $description[$name])->
                    where("payDate", '=<', $start)->where("payDate", ">=", $end)->
                    orderBy("payDate", "DESC")->
                    paginate(20);   

the model: 该模型:

<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;

class Payment extends Model
{
    protected $table = "payments";
    public $timestamps = false;
    protected $cast = ["payDate"=> "DATE"];
}

When the user makes a request for any of the ranges I wish to compare and give an answer. 当用户请求任何范围时,我希望进行比较并给出答案。

日期示例

the image for the database config is above and the structure below 数据库配置的图像在上方,结构在下方 表结构

You will have to use the STR_TO_DATE function of mysql. 您将必须使用mysql的STR_TO_DATE函数。

The raw SQL query you're looking for is: 您要查找的原始SQL查询是:

See it in action: http://sqlfiddle.com/#!9/a40090/8 实际操作中查看它: http : //sqlfiddle.com/#!9/a40090/8

select * from `test` where str_to_date(`payDate`, '%d-%m-%Y') > str_to_date('31-12-2007', '%d-%m-%Y');

With STR_TO_DATE you tell MySQL in what format the date is formatted which helps MySQL to give back the proper date for sorting and such. 使用STR_TO_DATE,您可以告诉MySQL日期的格式是什么格式,这有助于MySQL返回正确的排序日期。

Your Eloquent query will then come to look somewhat like this: 您的口才查询将看起来像这样:

 /** put it like this so we don't have to repeat it everywhere where needed **/
 $paydate_raw = DB::raw("STR_TO_DATE(`payDate`, '%d-%m-%Y')");

 /** encoding the raw query. the ? is populated by setBindings() **/
 $start_raw = DB::raw("STR_TO_DATE(?, '%d-%m-%Y')");
 $end_raw = DB::raw("STR_TO_DATE(?, '%d-%m-%Y')");


  $query = Payment::where($paydate_raw, '<', $start_raw)->where($paydate_raw, ">", $end_raw)->
                    orderBy('paydate', "DESC")->
                    setBindings([$start, $end])->
                    paginate(20);
  // debugging output.
  //echo $query->toSql();

Note the above code is just a concept, I haven't tested it out, but it should work. 请注意,以上代码只是一个概念,我尚未对其进行测试,但它应该可以工作。 Take a look also at the SQL fiddle to see how it should respond in raw. 还可以看一下SQL提琴,以了解它应该如何进行原始响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM