Laravel模型与数据库事务的序列化

时间:2018-08-22 12:39:01

标签: php laravel-5

我有一个应触发的事件,但是,当我调用使用DB::transaction的create方法时,收到一条错误消息,提示No query results for model [App\Model\Order\Order]。我知道我收到错误消息,因为该事件正在尝试序列化OrderModel,因为DB::transaction尚未创建。

如何避免此错误?

任何建议或建议将不胜感激。 预先谢谢你。

控制器

public function create() {
    DB::transaction(function () {
         $order = OrderModel::create([
                 'content' => 'bla bla'
             ]);

         event(new OrderDispatched($order));

         .... some other logics...
    });


    return response($order, 200);
}

事件

class OrderDispatched implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($order)
    {
        $this->order = $order;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new Channel('need-refresh');
    }

    public function broadcastWith()
    {
        return [
            'id' => $this->order->id,
            'carrier_team_id' => $this->order->carrier_team_id
        ];
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Laravel事务的其他语法:

public function create() 
{
    DB::beginTransaction();

    try {
        $order = OrderModel::create([
            'content' => 'bla bla'
        ]);

        DB::commit();

        // ... some other logic ...
    } catch(\Exception $e) {
        DB::rollBack();

        return response('Error', 500);
    }

    event(new OrderDispatched($order));

    return response($order, 200);
}

这样,您只会在事务没有失败的情况下发送事件。