我有mysql表:

Balance
id | client_id | balance

以及
Payments**
id | payment_date | amount | foreign key -> balance_id

当我存储付款金额时,使用什么方法更新余额?

最佳答案

在支付模型中,可以创建如下事件处理程序:

/**
 * The event map for the model.
 *
 * @var array
 */
protected $dispatchesEvents = [
    'created' => \App\Events\PaymentCreated::class,
];

然后您可以创建这样的事件:
支付CreatedEvent
<?php

namespace App\Events;

use App\Models\Payments;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;

class PaymentCreatedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $payments;

    /**
     * Create a new event instance.
     */
    public function __construct(Payments $payments)
    {
        $this->payments = $payments;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

然后可以创建一个侦听器来创建平衡:
PaymentCreatedListener付款
<?php

namespace App\Listeners;

use Illuminate\Support\Facades\Mail;
use App\Events\PaymentCreatedEvent;

class PaymentCreatedListener
{
    /**
     * Create the event listener.
     */
    public function __construct()
    {
    }

    /**
     * Handle the event.
     *
     * @param PaymentCreatedEvent $event
     */
    public function handle(PaymentCreatedEvent $event)
    {
        // Insert in to the balance table here
    }
}

然后在eventserviceprovider.php中添加
/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\PaymentCreatedEvent' => [
        'App\Listeners\PaymentCreatedListener',
    ],
];

听你的活动。您需要在侦听器中创建insert语句。。。但你明白了。

09-11 19:46
查看更多