【发布时间】:2020-12-15 16:35:48
【问题描述】:
我正在学习 Laravel 和 LightHouse,我正在尝试创建一个突变,它需要一个 DateTime 并将其放入数据库中。每次我通过 DateTime 进行突变时,输入都不会显示,只是被标记为 null,在数据库中触发错误,因为表不允许 DateTime 为 null。我所有的其他价值观都很好,所以我很困惑。 GraphQL Playground 抛出的错误是 SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column \"date_of_birth\" violates not-null constraint\nDETAIL: Failing row contains (17, Blaze, blaze@test.com, null, ABadPassword, null, 2020-08-26 19:54:38, 2020-08-26 19:54:38, null). (SQL: insert into \"users\" (\"username\", \"password\", \"email\", \"updated_at\", \"created_at\") values (Blaze, ABadPassword, blaze@test.com, 2020-08-26 19:54:38, 2020-08-26 19:54:38) returning \"id\")"
在 GraphQL Playground 中尝试的这个 Mutation:
mutation {
createUser(
username: "Blaze"
email: "blaze@test.com"
password: "ABadPassword"
date_of_birth: "1998-01-16 00:00:00"
){
id
}
}
这是我的架构:
"A date string with format `Y-m-d`, e.g. `2011-05-23`."
scalar Date @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\Date")
"A datetime string with format `Y-m-d H:i:s`, e.g. `2018-05-23 13:43:32`."
scalar DateTime @scalar(class: "Nuwave\\Lighthouse\\Schema\\Types\\Scalars\\DateTime")
type Mutation {
createUser(
username: String @rules(apply: ["required", "unique:users,username"]),
password: String @rules(apply: ["required"]),
email: String @rules(apply: ["required", "unique:users,email"]),
date_of_birth: DateTime @rules(apply: ["required"])
): User! @create
}
type User {
id: ID!
username: String!
email: String!
email_verified_at: DateTime
password: String!
created_at: DateTime!
updated_at: DateTime!
date_of_birth: DateTime!
}
这是应用程序中 User.php 文件中的我的用户:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'username', 'email', 'password',
'date_of_birth' => 'datetime'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
这是我在数据库中由迁移创建的表:
DatabaseName=# SELECT * FROM users;
id | username | email | email_verified_at | password | remember_token | created_at | updated_at|
date_of_birth
希望这为该错误提供了足够的上下文,并提前感谢您的帮助。
【问题讨论】:
-
您的数据库中的字段
date_of_birth是否可以为空? -
no
date_of_birth在数据库中不可为空,这就是它引发错误的原因。问题是我在突变中提供了date_of_birth,laravel 接收它,因为它是规则所要求的,但它向数据库发送了一个空值而不是输入的日期。这是我正在尝试解决的问题,而且很奇怪,因为我的所有其他输入都可以正常工作。
标签: php laravel postgresql graphql laravel-lighthouse