Laravelのタイムゾーンを使用して、デフォルトのデータベースDateFormatをISO 8601に設定します。
質問
タイトルはそれを言うと言っています。私はこの
を手に入れましたclass mEloquent extends Eloquent {
protected function getDateFormat()
{
return 'YYYY-MM-DDThh:mm:ss.sTZD';
}
}
.
私のすべてのモデルはメロケントを拡張します。しかし、どのように私はテーブルを構築すべきですか?ただ
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('firstName');
$table->string('lastName');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
} ......
.
通常どおり? このDateFormatを比較する方法またはShoud私はデフォルトのものを使い、タイムゾーンを別々に保存しますか?
解決
あなたが文書に従うならば、それは本当に簡単です。
PHP date
関数は、PHP5以降、PHP5以降、'c'
フォーマット文字を渡すことで取得できます。
http://php.net/manual/en/function.date.php
Laravel Modelは日付属性をCarbon
オブジェクトに変換します。CarbonはDateTime
のすべてのformat
フォーマット文字をサポートするdate
を伸びています。
日付属性を変更するには、アクセサ(または新しいカスタム属性でさえも簡単に作成できます。次に、炭素format
メソッドを使用して、 ISO 8601 形式に変更します。
SO LARAVERモデルでは、このようなものをすることができます:
public function getPublishedAt8601Attribute()
{
return $this->published_at->format('c');
}
.
// Prints something like: 2016-10-13T21:48:00+03:00
echo $post->published_at_8601;
. 他のヒント
ドキュメントに記載されているように、これを基本クラス 'Meloquent'
に追加します。/**
* The storage format of the model's date columns.
*
* @var string
*/
protected $dateFormat = 'c';
.
日付のシリアライズをチェックすることもできます。 https://laravel.com/docs/5.6/eLoquent-serialization#date-直列化
$date = Carbon::now();
echo $date->toW3cString();
$date = $this->repository->find($id);
echo $date->created_at->toW3cString();
.
出力
2018-04-14T18:35:58 + 00:00
所属していません StackOverflow