简体   繁体   中英

laravel, convert stored date format in a model to use whereBetween

I want to use whereBetween to get date interval, for created_date it works fine:

$data = Userorder::whereBetween('created_at', [$dateS->format('Y-m-d')." 00:00:00", $dateE->format('Y-m-d')." 23:59:59"])->get();

But I have another column name order_date where this column have the date in the format: Fri Jan,24,2020 so I want to convert it to the format Ymd

$dateS = new Carbon($startdate);
$dateE = new Carbon($enddate);
$data = Userorder::whereBetween('order_date', [$dateS->format('Y-m-d'), $dateE->format('Y-m-d')])->get();

Model:

class Userorder extends Model
{
    protected $table = "userorders";
    protected $fillable = [
        'order_number',
        'product_id',
        'order_time',
        'order_date',
        'product_qty',
        'product_price',
        'product_totalprice',
        'totalprice',
        'product_instruction',
        'product_size',
        'storeinfo_id',
        'product_serve',
        'user_id',
        'user_distance',
        'user_address',
        'user_instruction',
        'office_name',
        'st_address',
        'order_state',
        'order_city',
        'order_zipcode',
        'gratuity',
        'suite_floor',
        'driver_ask',
        'phone_number',
        'paid',
        'isdelivery',
        'deliveredon',
        'show',
        'confirmed',
        'isonline',
        'houseaccount'
    ];
    protected $primaryKey = 'id';
    public $timestamps = true;

To achieve what you're after you should be able to use Laravel's whereRaw() method in conjunction with MySQL's STR_TO_DATE() function ( mysql date format strings ):

Userorder::whereRaw('STR_TO_DATE(order_date, "%a %b,%d,%Y") between ? and ?', [$dateS->format('Y-m-d'), $dateE->format('Y-m-d')])->get();

This being said, if possible I would recommend updating your table (and related code) so that the order_date is actually a date column and not just a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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