支付后,Laravel mysql更新余额

时间:2018-01-21 19:56:35

标签: mysql laravel

我有mysql表:

Balance
id | client_id | balance

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

存储付款金额时,使用哪些方法更新余额?

2 个答案:

答案 0 :(得分:0)

在付款模式中,您可以创建如下的事件处理程序:

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

然后你可以创建一个这样的事件:

<强> PaymentCreatedEvent

<?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语句......但是你明白了。

答案 1 :(得分:0)

在付款问题上,我认为您必须处理交易并检查所有插入/更新是否成功运行。

您可以采用以下方法之一:

1。 在您的付款方式中:

static function boot() {
    static::created(function($payment){
        //update balance here
    }
}

2。    在您的控制器或其他类中:

DB::beginTransaction();

try{

    //insert payment row

    //update balance

    DB::commit();
}
catch (\Exception $e){
    DB::rollback();
}