在创建房间时在床单中插入数据

时间:2018-01-29 08:05:00

标签: php laravel laravel-5.5

我有房间迁移

Schema::create('rooms', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('floor');
            $table->integer('beds'); //number of beds in each room
            $table->integer('room_type_id')->unsigned();
            $table->foreign('room_type_id')->references('id'->on('room_types')
                  ->onUpdate('cascade')->onDelete('cascade');
            $table->text('description')->nullable();
        });

和床迁移

Schema::create('beds', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->default('1');
            $table->decimal('charge');
            $table->boolean('available')->default(1);
            $table->integer('room_id')->unsigned();
            $table->foreign('room_id')->references('id')->on('rooms')
                  ->onUpdate('cascade')->onDelete('cascade');
            $table->boolean('status')->default(1);
            $table->timestamps(); 
        });

我想在我添加新房间的同时根据房间桌子的床位添加床的数量,并给床名1,2,3,4等等

1 个答案:

答案 0 :(得分:0)

我使用事件监听器

public function handle(createRoom $event)
    {

        for ($i =1; $i <= $event->room->beds; $i++) 
        {
            $bed = new Bed();
            $bed->name = $i;
            $bed->charge = '100';
            $bed->room_id = $event->room->id;
            $bed->save();
        }
    }
}