Eloquentを使う際にちょっと便利になるTipsをまとめてみました。
網羅性はないので参考程度に。
$table
を定義することで任意のテーブルへのアクセス出来ます。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
protected $table = 'custom_example';
}
$primaryKey
を定義して変更することが可能です。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
// デフォルトは'id'で定義されています。
protected $primaryKey = 'custom_key';
}
$keyType
を定義して変更することが可能です。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
// デフォルトは'int'で定義されています。
protected $keyType = 'string';
}
$incrementing
を定義して変更することが可能です。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
// デフォルトはtrueで定義されています。
protected $incrementing = false;
}
$timestamps
を定義することでデフォルトのタイムスタンプを使用しなくなります。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
// デフォルトはtrueで定義されています。
public $timestamps = false;
}
詳細はIlluminate\Database\Eloquent\Concerns\HasTimestamps
を参照してください。
モデルクラスにCREATED_AT
、UPDATED_AT
を定義することで変更できます。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
const CREATED_AT = 'created';
const UPDATED_AT = 'updated';
}
次のようなマイグレーションを作成します。
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateSampleTable extends Migration
{
public function up()
{
Schema::create('sample', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('text');
// created_at, updated_atカラムが追加されます。
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('sample');
}
}
モデルクラスをSample
とした時、次のような実行が可能です。
<?php
namespace App\Http\Controllers;
use App\Sample;
class HomeController extends Controller
{
public function index()
{
/** @var App\Sample $sample */
$sample = Sample::find(1);
// 時刻の差分を取得
$diff = $sample->created_at->diffForHumans();
}
}
created_at
、updated_at
にアクセスすると、Carbon
オブジェクトに変換してくれています。
そのため、diffForHumans
などのメソッドが呼び出せます。
詳細はIlluminate\Database\Eloquent\Concerns\HasAttributes
を参照してください。
また、独自にCarbon
オブジェクトで受け取りたいカラムを設定したい場合は$dates
を定義することで可能です。
<?php
use Illuminate\Database\Eloquent\Model;
class Example extends Model
{
// created_at, updated_at以外のカラム名を追加します。
protected $dates = [
'created', 'updated'
];
}
Crieitは誰でも投稿できるサービスです。 是非記事の投稿をお願いします。どんな軽い内容でも投稿できます。
また、「こんな記事が読みたいけど見つからない!」という方は是非記事投稿リクエストボードへ!
こじんまりと作業ログやメモ、進捗を書き残しておきたい方はボード機能をご利用ください。
ボードとは?
コメント