我最近将数据库从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]);
}
我的QuizTopic模型
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();
}
}
我的QuizQuestion模型
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();
}
}
答案 0 :(得分:1)
从手册:
默认情况下,时间戳记格式为“ Y-m-d H:i:s”。如果你需要 自定义时间戳格式,在您的网站上设置$ dateFormat属性 模型。此属性确定日期属性如何存储在 数据库,以及将模型序列化为 数组或JSON
(重点是我的)
由于将日期另存为Y-m-d H:i:s.000
,因此需要在两个模型中都这样设置$dateFormat
属性:
protected $dateFormat = 'Y-m-d H:i:s.000';
对此进行更改,然后重试。