【问题标题】:Laravel livewire wire:model with arrayLaravel livewire 线:带数组的模型
【发布时间】:2021-09-14 02:53:29
【问题描述】:

我可以从刀片组件中给出有价值的 product_id

<input wire:model="qty.{{$row->product_id}}" value="{{$row->qty}}" max="{{$row->stock}}">

但是我如何从数据库中显示数量,当增加数量时,线模型将工作并更新,我该怎么办???

public $qty;
    

    public function render()
    {
        $this->userId=Auth::id();

        if ($this->qty!=null){

            foreach($this->qty as $key => $qty)
            {
                $cart=Cart::where('user_id',$this->userId)->where('product_id',$key)->first();

                if ($cart){
                    $cart->update([
                        'qty'    =>  $qty,
                    ]);
                    $this->emit('refreshCart');
                }

            }

        }

    }

【问题讨论】:

    标签: laravel laravel-livewire


    【解决方案1】:

    在你的刀片中

    <input wire:model="inputs.{{ $loop->index }}.qty" value="{{$row->qty}}" max="{{$row->stock}}">
    <a wire:click.prevent="increase({{$loop->index}})"></a>
    <a wire:click.prevent="reduce({{$loop->index}})"></a>
    

    在你的 livewire 组件中

    public $inputs = [];
    
        public function mount()
        {
            foreach (Cart::where('user_id',$this->userId)->get() as $item) {
                array_push($this->inputs, [
                    "id" => $item->id,
                    "qty" => $item->quantity,
                ]);
    
            }
        }
        public function reduce($index)
        {
            $product_id = $this->inputs[$index]['id'];
            $this->inputs[$index]['qty'] -= 1;
            $this->updateCart($product_id, $this->inputs[$index]['qty']);
        }
        public function increase($index)
        {
            $product_id = $this->inputs[$index]['id'];
            $this->inputs[$index]['qty'] += 1;
            $this->updateCart($product_id, $this->inputs[$index]['qty']);
        }
        public function updateCart($product_id, $productQty)
        {
            //update yourcart here with productID and qty
        }
    

    此代码对我有用。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-09-10
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2021-04-10
    • 2021-09-12
    相关资源
    最近更新 更多