我有 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,
];
然后你可以像这样创建一个事件:
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',
],
];
收听您的事件。您将需要在监听器中创建插入语句...但您明白了。
关于mysql - Laravel mysql 付款后更新余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48371079/