Convert DATE_FORMAT to Y-m-d? Using Larave Eloquent Raw Select

徘徊边缘 提交于 2021-02-11 12:29:00

问题


Currently I have this eloquent select in laravel

$queryBooking = Booking::where('id',$id)->select('starts_at','ends_at')->first();

Now I want to put specific format to starts_at and ends_at using this format Y-m-d

Data should be shown somethings like this 2020-05-29 (Y-m-d)

How can I do that using laravel eloquent?

UPDATE

tried the answer of spiny did some modification.

 $queryBooking = Booking::where('id',$id)->select('starts_at','ends_at')->first();

 $booking = PropertyBooking::where('property_id',$queryBooking->property_id)
    ->selectRaw(
        'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
    )->get();

    return view('admin.pages.property_request.edit', compact('property_request','booking'));

in my blade tried to log it using js says like this


回答1:


Just add some properties to your booking. The date attribute converts the column to carbon. The dateFormat attribute is the default format for converting dates to String

example

class Booking extends Model
{
    protected $dates = ['starts_at','ends_at'];
    protected $dateFormat = 'Y-m-d';
    ....
}



回答2:


How about this:

->selectRaw(
    'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
)

Also you can use it as a scope:

public function scopeSelectStartEndDates($query) {
    return $query->selectRaw(
        'DATE_FORMAT(`starts_at`, "%Y-%m-%d") AS `starts_at`, DATE_FORMAT(`ends_at`, "%Y-%m-%d") AS `ends_at`'
    );
}
$model = Model::selectStartEndDates()->first();


来源:https://stackoverflow.com/questions/61767273/convert-date-format-to-y-m-d-using-larave-eloquent-raw-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!