Blogger Information
Blog 47
fans 0
comment 3
visits 45059
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Laravel实现将数据库操作记入日志
江流
Original
1317 people have browsed it

日志数据表迁移文件

  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\Schema;
  5. class CreateLogsTable extends Migration
  6. {
  7. /**
  8. * Run the migrations.
  9. *
  10. * @return void
  11. */
  12. public function up()
  13. {
  14. Schema::create('logs', function (Blueprint $table) {
  15. $table->id();
  16. $table->string('username',50)->comment('用户名');
  17. $table->string('query')->comment('SQL语句');
  18. $table->string('para')->comment('参数');
  19. $table->timestamps();
  20. });
  21. }
  22. /**
  23. * Reverse the migrations.
  24. *
  25. * @return void
  26. */
  27. public function down()
  28. {
  29. Schema::dropIfExists('logs');
  30. }
  31. }

Log 模型文件

  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. class Log extends Model
  6. {
  7. use HasFactory;
  8. protected $guarded=[];
  9. }

存入日志记录表

  1. //启用数据操作日志
  2. DB::enableQueryLog();
  3. Book::create(['name'=>'Laravel框架']);
  4. $log['username']="admin";
  5. //(DB::getQueryLog()获取操作日志,是一个二维数组
  6. foreach(DB::getQueryLog() as $operation){
  7. $log['query']=$operation['query'];
  8. $log['para']="";
  9. foreach ($operation['bindings'] as $para){
  10. $log['para'].=$para.",";
  11. }
  12. Log::create($log);
  13. }

以上代码,以使用模型进行数据的添加为例进行说明的,模型的其他操作同样可以写入日志,使用构造查询器也可以将对数据的操作存入日志

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post