【发布时间】:2018-08-20 19:13:28
【问题描述】:
我最近将我的数据库从 MySql 更改为 MSSql,但我遇到了日期格式问题。我将所有模型更改为使用 $dateFormat = 'Y-m-d H:i:s' 并且工作正常,但是今天我遇到了与其他模型具有多对多关系的模型的问题。
我的数据库以 Y-m-d H:i:s.000 格式保存日期,即 2018-08-20 16:01:12.000。我认为雄辩不尊重日期格式。
我正在使用 Laravel 5.4 和 php 5.6;
今天,我收到了这个错误
InvalidArgumentException in Carbon.php line 909:
Data missing
in Carbon.php line 909
at Carbon::createFromFormat('Y-m-d H:i:s.000', '2018-07-19 10:40:21') in Model.php line 3003
产生错误的代码,
public function getDetailQuiz()
{
$quiz_id = Input::get('quiz_id');
*$quiz = QuizTopic::with('questions.answers')->where('id', $quiz_id)->first();*
foreach ($quiz->questions as $question) {
$answers = [];
$answer_order = 0;
foreach ($question->answers as $i => $answer) {
$answers[] = ['answer' => $answer->description, 'id' => $answer->id, 'action' => 'update'];
if ($question->answer_id == $answer->id) $answer_order = $i;
}
$response['questions'][] = [
'id' => $question->id,
'question' => $question->description,
'correct_answer' => $question->answer_id,
'points' => $question->points,
'answers' => $answers,
'action' => 'update',
'answer_order' => $answer_order,
];
}
$quiz->start_date = Carbon::parse($quiz->start_date)->format('d/m/Y H:i');
$quiz->end_date = Carbon::parse($quiz->end_date)->format('d/m/Y H:i');
$response['quiz'] = $quiz->makeVisible(['award_value', 'type_id', 'start_date', 'end_date'])->toArray();
return response()->json(['result' => $response]);
}
我的测验主题模型
class QuizTopic extends Model
{
protected $table = 'quiz_topics';
protected $guarded = ['id'];
protected $hidden = [
'created_at',
'updated_at',
'deleted_at',
'created_user_id',
'updated_user_id',
'winner_clerk_id',
'award_value',
'status_id',
'type_id',
'start_date',
'end_date',
'raffle_date',
'fcm_notification_reference',
];
protected $dateFormat = 'Y-m-d H:i';
use SoftDeletes;
public function questions()
{
return $this->belongsToMany('App\Models\QuizQuestion', 'rel_topics_questions', 'topic_id', 'question_id')->withTimestamps();
}
}
我的测验问题模型
class QuizQuestion extends Model
{
protected $table = 'quiz_questions';
protected $guarded = ['id'];
protected $hidden = ['created_at', 'updated_at', 'deleted_at','points','pivot','created_user_id','updated_user_id'];
protected $dateFormat = 'Y-m-d H:i:s';
use SoftDeletes;
public function topics()
{
return $this->belongsToMany('App\Models\QuizTopic');
}
public function answers()
{
return $this->belongsToMany('App\Models\QuizAnswer', 'rel_questions_answers', 'question_id', 'answer_id')->withTimestamps();
}
}
【问题讨论】:
-
您说您正在以
Y-m-d H:i:s.000格式存储日期,但 Carbon 正在尝试转换没有毫秒的日期2018-07-19 10:40:21。您确定存储的日期格式正确吗? -
奇怪,因为所有其他型号都没有同样的问题,仅此而已。我会尝试更改格式并保存并获取结果进行测试。
标签: laravel php-carbon