事件未记录在Laravel的表格中

lx0bsm1f  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(147)

我正在从books表中删除一条记录,该表通过外键book_id自动删除loans表中该记录的键,我创建了一个事件来创建一个日志,该日志记录删除loans表中存储books table ($table->foreignId('book_id')->constrained('books')->onDelete( 'cascade');记录的外键的列,但logs_deletions表中未记录该事件。

  • BookDeletedEvent.php
<?php
    
    namespace App\Events;
    
    use Illuminate\Broadcasting\Channel;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Broadcasting\PresenceChannel;
    use Illuminate\Broadcasting\PrivateChannel;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Queue\SerializesModels;
    
    class BookDeletedEvent
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;
        public $deleted_id;
    
        /**
         * Create a new event instance.
         *
         * @return void
         */
        public function __construct($deleted_id)
        {
            $this->deleted_id = $deleted_id;
        }
    
        /**
         * Get the channels the event should broadcast on.
         *
         * @return \Illuminate\Broadcasting\Channel|array
         */
        public function broadcastOn()
        {
            return new PrivateChannel('channel-name');
        }
    }
  • EventServiceProvider.php
<?php
    
    namespace App\Providers;
    
    use Illuminate\Auth\Events\Registered;
    use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
    use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
    use Illuminate\Support\Carbon;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Event;
    use App\Events\BookDeletedEvent;
    
    class EventServiceProvider extends ServiceProvider
    {
        /**
         * The event to listener mappings for the application.
         *
         * @var array<class-string, array<int, class-string>>
         */
        protected $listen = [
            Registered::class => [
                SendEmailVerificationNotification::class,
            ],
        ];
    
        /**
         * Register any events for your application.
         *
         * @return void
         */
        public function boot()
        {
            Event::listen('BookDeletedEvent', function ($event) {
                DB::table('logs_deletions')->insert([
                    'description' => "The Book ID Nº$event->deleted_id was automatically deleted from the loans table.",
                    'date' => Carbon::now()->format('d/m/Y H:i:s'),
                ]);
                DB::table('loans')->where('book_id', $event->deleted_id)->delete();
                event(new BookDeletedEvent($event->deleted_id));
            });
        }
    
        /**
         * Determine if events and listeners should be automatically discovered.
         *
         * @return bool
         */
        public function shouldDiscoverEvents()
        {
            return false;
        }
    }
  • logs_deletions_table.php
<?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('logs_deletions', function (Blueprint $table) {
                $table->id();
                $table->longText('description');
                $table->timestamp('date')->useCurrent();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('logs_deletions');
        }
    };
  • LogDeletionFKModel.php
<?php
    
    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    class LogDeletionFKModel extends Model
    {
        use HasFactory;
        protected $table = 'logs_deletions';
        protected $primaryKey = 'id';
        protected $fillable = [
            'description',
            'date',
        ];
    }

代码没有显示任何可见的问题,只是没有在表中记录事件。

dauxcl2d

dauxcl2d1#

我认为您需要掌握事件和侦听器的基本定义。
https://laravel.com/docs/9.x/events#registering-events-and-listeners
BookDeletedEvent是一个事件。
当事件被触发时,将调用在EventServiceProvider内正确Map的侦听器类。
所以你要做的就是

  • 通过执行创建监听程序

第一个月

  • 将EventServiceProvider Boot ()方法中的一些代码移到此侦听器handle()方法中。
public class handle(BookDeletedEvent $event)
    {
        DB::table('loans')
            ->where('book_id', $event->deleted_id)
            ->delete();
        DB::table('logs_deletions')->insert([
           'description' => "The Book ID Nº$event->deleted_id was automatically deleted from the loans table.",
           'date' => now()->format('d/m/Y H:i:s'),
        ]);
    }
  • 而不是返回到事件服务提供程序
  • 删除 Boot ()中的代码
  • 注册你的事件+监听器
protected $listen = [
        Registered::class => [
             SendEmailVerificationNotification::class,
        ],
        BookDeletedEvent::class => [
             DeleteBookAndLogIt::class,
        ],
    ];
  • 现在您可以使用event(new BookDeletedEvent($book_id));从控制器或服务类内部调用/执行此事件

相关问题