【问题标题】:Convert DATE_FORMAT to Y-m-d? Using Larave Eloquent Raw Select将 DATE_FORMAT 转换为 Y-m-d?使用 Larave Eloquent 原始选择
【发布时间】:2020-05-13 05:46:47
【问题描述】:

目前我在 laravel 中有这个雄辩的选择

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

现在我想将特定格式放入starts_atends_at 使用这种格式Y-m-d

数据应显示为2020-05-29(Y-m-d)

如何使用 laravel eloquent 做到这一点?

更新

尝试了 spiny 的答案做了一些修改。

 $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'));

在我的刀片中尝试使用 js 记录它是这样说的

【问题讨论】:

  • date('Y-m-d',strtotime($queryBooking->starts_at)) 试试这个方法。
  • 它会给我预期的输出,但我正在尝试以雄辩的方式工作..

标签: php laravel eloquent


【解决方案1】:

只需在您的预订中添加一些属性。 date 属性将列转换为碳。 dateFormat 属性是将日期转换为字符串的默认格式

例子

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

【讨论】:

  • 嗨,我怎样才能将它应用到我的查询中?如果我的`模型`上已经有了protected
  • 为我的错误道歉 $queryBooking->starts_at->format('Y-m-d);
  • 它说,尾随数据.. 嗯
【解决方案2】:

这个怎么样:

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

您也可以将其用作范围:

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();

【讨论】:

  • selectRaw 将是答案,但我仍然得到时间戳。它包括时间,它应该只是 YYYY-MM-DD。 :(
  • 如果是这样,你做错了,伙计。你能提供我的例子的代码吗?
  • 您的结果显示$queryBooking 而不是$booking,因为$queryBooking->property_id 为空(您没有从$queryBooking 的选择中得到它)。所以,要多加注意,先将其添加到查询选择中:$queryBooking = Booking::where('id',$id)->select('property_id', 'starts_at','ends_at')->first(); ;)
猜你喜欢
  • 1970-01-01
  • 2021-05-16
  • 2023-03-08
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多