【问题标题】:Laravel complaining about 'trailing data' when sending ISO-formatted date in JSON to server?Laravel 在向服务器发送 JSON 格式的 ISO 格式日期时抱怨“跟踪数据”?
【发布时间】:2018-03-19 00:35:55
【问题描述】:

我有一个带有日期字段archivedAt 的 Laravel 模型。这已在模型上的$dates 数组中设置,如下所示:

联系模特

class Contact extends Model
{
    /**
     * The name of the table in the database.
     *
     * @laravel-table-name
     *
     * @var string
     */
    protected $table = 'Contacts';

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = [
        'createdAt',
        'updatedAt',
        'archivedAt'
    ];

}

当我尝试通过 GraphQL 向服务器发送 JSON 有效负载时,我收到以下响应:

{
    "data": {
        "editContact": null
    },
    "errors": [
        {
            "message": "Unexpected data found.\nTrailing data",
            "locations": [
                {
                    "line": 2,
                    "column": 3
                }
            ]
        }
    ]
}

当然,Laravel 的 GraphQL 库很糟糕,并且不包含完整的堆栈跟踪或任何其他信息,但这似乎是我设置 archivedAt 字段的问题。以下是我的做法:

{
    "operationName": null,
    "variables": {
        "contactEditForm": {
            "id": "2",
            "name": "Maybelle Collier",
            "email": "cletus49@example.org",
            "phone": "+1 (997) 381-8483",
            "archivedAt": "2018-03-19T00:07:57.191Z",
            "createdAt": "2018-03-18 23:57:30",
            "updatedAt": "2018-03-18 23:57:30"
        }
    },
    "query": "mutation ($contactEditForm: ContactEditForm!) {\n  editContact(contactEditForm: $contactEditForm) {\n    id\n    name\n    __typename\n  }\n}\n"
}

如您所见,archivedAt 是一个 ISO8601 格式的字符串,它是在我的客户端上生成的:

(new Date())->toISOString();

然后应该将其保存在带有突变的 GraphQL 服务器上,如下所示:

public function resolve($root, $args, $context, ResolveInfo $info)
{
    $contact = Contact::find($args['contactEditForm']['id']);
    $contact->fill($args['contactEditForm']);
    $contact->save();

    return $contact;
}

为什么 Laravel 不喜欢这样?

【问题讨论】:

  • Laravel 中的所有日期都被视为碳日期。阅读Carbon docs
  • @Maramal 是的,我知道这一点。
  • 我认为我们需要您的后端代码(在控制器方面)来理解问题。
  • @Maramal GraphQL 没有控制器的概念。我已在填充联系人的位置附加了突变解析器。

标签: javascript laravel date iso8601


【解决方案1】:

我从来没有遇到过这个问题,但是根据Laravel's Docs,如果您在 $dates 属性中设置该字段,则可以正确更改:

当一列被视为日期时,您可以将其值设置为 UNIX 时间戳、日期字符串 (Y-m-d)、日期时间字符串,当然还有 DateTime / Carbon 实例,并且日期的值将自动为 正确存储在您的数据库中:

因此,显然,不允许对 mutator 使用 ISO 字符串日期,因此要么将其设置为其中一种格式,defining an acessor (like this),要么将其从 $dates 中删除并自行处理

http://carbon.nesbot.com/docs/#api-commonformats

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2023-01-03
    • 2019-01-30
    • 2015-02-28
    • 1970-01-01
    • 2015-09-12
    相关资源
    最近更新 更多