在Laravel 5.4

时间:2018-03-13 10:52:54

标签: php laravel eloquent laravel-5.4

我有两个模型:EventTicket。我在他们之间分配了Many-To-Many关系:这是:

Ticket型号:

public function events()
{
    return $this->belongsToMany('App\Event');
}

Event型号:

public function tickets()
{
    return $this->belongsToMany('App\Ticket');
}

然后我在我的Controller中想要更新pivot表数据:

public function register(Request $request)
{
    $event = Event::findOrFail($request->event);
    if(count($event) > 0) {

        foreach($request->tickets_type as $key => $value) {
            if($value !== null) {
                for($i = 0; $i < (int) $value; $i++) {
                    $sale = new Sale;
                    $sale->event_id = $request->event;
                    $sale->event_type = $request->event_type;
                    $sale->user_id = Auth::user()->id;
                    $sale->ticket_type = $key;
                    $sale->save();

                    $sale->qr = $this->generateQR($sale->event_id, $sale->ticket_type, $sale->id);
                    $sale->update();                        
                }

                $event->tickets->pivot->ticket_quantity -= $value;
            }
        }        

        return response()->json([
            'success' => true,
            'message' => 'Покупка билетов успешно завершена.',
            'data' => $request->all()
        ], 200); 

    } else {
        return response()->json([
            'success' => false,
            'error' => 'Попытка подмены данных.'
        ], 403);  
    }        
}

$event->tickets->pivot->ticket_quantity -= $value;上,它会抛出一个错误:

  

此集合实例上不存在Property [pivot]。

解决方法是什么?

1 个答案:

答案 0 :(得分:0)

更改此

$event->tickets->pivot->ticket_quantity -= $value;

到这个

$vent->tickets()->attach(id, ['ticket_quantity' => $value]);

您还可以使用同步删除输入中不在的额外条目

$vent->tickets()->sync(id, ['ticket_quantity' => $value]);

希望这有帮助