RatkoR / laravel-crate.io

Crate.io driver for Laravel
MIT License
36 stars 12 forks source link

Laravel Carbon dates #29

Open olavski opened 5 years ago

olavski commented 5 years ago

Hi,

I see there is a pull request related to date format, so I thought I'd just show how I handle datetime with Eloquent.

Currently when saving dates (INSERT/UPDATE) CrateDB accepts 'Y-m-dTH:i:s' format, but when querying (SELECT) it returns a millisecond timestamp.

I've created a Eloquent model trait that makes CrateDB models handle DateTime fields same way as with MySQL: https://github.com/web64/laravel-cratedb-demo/blob/master/app/Models/Traits/HasCrateDates.php

<?php

namespace App;

use RatkoR\Crate\Eloquent\Model AS Eloquent;

class MyModel extends Eloquent
{
    use HasCrateDates;

    protected $connection = 'crate';
    protected $dates = ['modified_at', 'published_at];
} 

Then you can use Carbon dates:

$model = MyModel::create([
    'modified_at' => now(),
    'published_at' => now()->subDays(3),
]);

$model = MyModel::latest()->get();
$model->modified_at; // Carbon instance
$model->published_at->diffForHumans(); // '3 days ago'

As this is a optional trait that can be added to models, there is full backward compatability and no changes needed in the core laravel-crate.io library.

Please note this is a work-in-progress and not fully tested.

Cheers, Olav

JulianMar commented 4 years ago

You solution gives me a Fatal Error. You trait and the Eloquent Model both have the property dateFormat defined.

olavski commented 4 years ago

Ok, I'll have another look at it.

JulianMar commented 4 years ago

I think you can just remove the dateFormat property and it should work aswell