14

我正在尝试获得 Eloquent 查询结果,DB::raw("DATE_FORMAT(created_at, '%m-%d-%Y %r') AS created_at")但每次我从 Carbon 收到此异常时:

InvalidArgumentException
Unexpected data found. Trailing data

如果我将其更改为只是created_at不使用 MySQL 的DATE_FORMAT()功能,那么它可以毫无问题地获取数据。

我以前不仅没有问题地完成过这种日期格式,而且我检查了数据库表中的每个字段(这个种子只有 10 个)并且每个都是标准的有效日期,所以我想知道为什么 Carbon 会投球适合。

在 Laravel 4.1 中运行它。

4

3 回答 3

25

Eloquent查询结果(模型)中,每个date字段都是一个碳对象,这意味着,如果您查询包含任何timestamp字段的模型created_atupdated_at (基本上是timestamps()在迁移期间使用创建的)和deleted_atLaravel将它们转换为Carbon对象,您可以使用任何公共方法Carbon, 例如:

$user = User::find(1);

// '2014-04-20 19:02:09' will become 'Apr 20, 2014'
$user->created_at->toFormattedDateString();

因此,您可以直接在模型中可用的字段Carbon上使用任何公共方法。timestamp如果你试试这个:

dd($user->created_at);

然后输出将是:

object(Carbon\Carbon)[456]
  public 'date' => string '2014-04-20 19:02:09' (length=19)
  public 'timezone_type' => int 3
  public 'timezone' => string 'UTC' (length=3)

所以,如果你想format约会,你可以使用:

// outputs like: 'Sunday 20th of April 2014 07:02:09 PM'
$user->created_at->format('l jS \\of F Y h:i:s A')

更新:

如果你想改变这种行为,这意味着,如果你想告诉Laravel,哪些字段应该自动转换为Carbon对象,那么你可以通过在你的模型中创建一个方法来覆盖它:

public function getDates()
{
    // only this field will be converted to Carbon
    return array('updated_at');
}

getDates要完全禁用日期突变,只需从方法中返回一个空数组。有关更多详细信息,请查看网站上的Date MutatorsLaravel

于 2014-06-11T20:03:45.067 回答
6

我意识到最初的问题是指 MySQL,但我对 MSSQL 有同样的错误。问题原来是 MSSQL 的 datetime 列类型的精度为 0.001 秒,但我将模型的格式设置为无精度:

protected function getDateFormat()
{
    return 'Y-m-d G:i:s';
}

通过使用较新的 DateTime2 列类型并关闭精度,我修复了错误。IE

datetime2(0)

当然,您可以改为更改格式getDateFormat

于 2015-06-02T07:58:27.313 回答
0

如果它对其他人有帮助,我在尝试复制日期时会遇到同样的错误。

$user->last_login = Carbon::now();

if ($user->first_login < Carbon::createFromDate(2000, 1, 1)) {
    // This is the users first login
    $user->first_login = $user->last_login; // FAILS!
}

原来 Laravel 将值转换$user->last_login为 DateTime+Timezone 字符串。它不再是 Carbon 对象。

您可以通过使用单个 Carbon 对象的副本(下面的示例)或通过在底层模型上设置 mutator(setter)来修复错误。

$now = Carbon::now();
$user->last_login = $now;

if ($user->first_login < Carbon::createFromDate(2000, 1, 1)) {
    // This is the users first login
    $user->first_login = $now;
}
于 2016-04-19T01:43:29.477 回答