# Laravel timestamp() auto update 有効化無効化

Laravel のマイクロフレームワーク Lumen を利用して migration 作成する時に timestamp 自動 update のメモです。Mysql のやり方では Sqlite3 がサポートしていないため少し困りました。

# Mysql migration updated_at 自動 timestamp 化

この方法は **Mysql** のみに利用できます

Mysql のCURRENT_TIMESTAMP on update CURRENT_TIMESTAMPを利用することで、レコード更新 update された時に自動的に timestamp 貼る作業ができます。sqlite には使えません




















 
 
















use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();

            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));

            // $table->timestamps(); 本来created_at updated_atのデフォルト
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

# created_at updated_at timestamp 無効化







 
 


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Products extends Model
{
    const CREATED_AT = NULL;
    const UPDATED_AT = NULL;
}

CREATED_AT UPDATED_AT のいずれかをNULLにすれば、無効化できます。

# Sqlite で updated_at timestamp 自動化

やり方はありますが、簡単ですぐにできそうなものがなさそうです。

引き続き調査更新します。

2021-06-25

同じタグを持つ記事をピックアップしました。