【问题标题】:Save extra field on pivot table laravel/vue在数据透视表 laravel/vue 上保存额外字段
【发布时间】:2021-06-03 09:14:27
【问题描述】:

我有一个发票表、一个项目表和一个数据透视表 invoice_items。 Inovice_items 表有一个字段数量,用于保存特定发票上每个项目的保存数量。

在 Invoice 中添加项目是使用 Vue.js 创建的。如何在数据透视表中保存 vue 的数量?

代码 物品模态

<template>
    <div>
        <div class="modal fade" id="itemsModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Select an Item</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" data-backdrop="false" data-toggle="modal" data-target="#itemsModal"  aria-label="Close"></button>
                    </div>
                    <div class="modal-body" >
                        <select class="form-select  mb-3"  v-if="items" @change="getSelectedItem($event)">
                            <option selected>-Select an Item-</option>
                            <option v-for="item in items " 
                                    :key="item.id"
                                    :value="item.id"
                                    >{{ item.name }}</option>
                        </select>
                          <div class="m-4">
                              <label for="">Sales Price</label><br>
                              <p class="price">{{ selectedItem.sales_price }} $</p>
                         </div>
                          <div class="m-4">
                            <label for="">Quantity</label><br>
                            <input type="number" class="form-control" v-model="selectedItem.quantity" name="quantity">
                         </div>
                          <div class="m-4">
                              <label for="">Total</label><br>
                                <p class="price">{{ totalPrice }} $</p>
                         </div>
                         <span class="btn btn-success" @click="addInvoiceItem">Add</span>
                    </div>
                  
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    name: 'ItemsModal',
    mounted(){
        this.getItems()
    },
    data(){
        return{
            items: [],
            selectedItem: { 
            },

        }
    },
    methods:{
        getItems(){
            axios.get('http://127.0.0.1:8000/data/all-items').then(response => {
                this.items = response.data
            })
        },
        getSelectedItem(event){
            axios.get('http://127.0.0.1:8000/items/' + event.target.value).then(response => {
                this.selectedItem = response.data.item
            })
        },
        addInvoiceItem(){
            this.$emit('selected-item',  this.selectedItem )
            this.selectedItem = {}
            $('#itemsModal').toggle()
            $('.modal-backdrop').hide()
        }
    },
    computed:{
        totalPrice(){
            let total = 0;
            total += (this.selectedItem.sales_price * this.selectedItem.quantity)
            this.selectedItem.total = total
            return total
        }
    }

}
</script>

发票控制器

public function store(Request $request)
    {

             $invoice = Invoice::create([
            'invoice_no' => 'invoice',
            'invoice_date'=> $request->input('invoice_date'),
            'due_date'=> $request->input('due_date'),
            'customer_id'=> $request->input('customer_id'),
            'sub_total' => $request->input('sub_total'),
            'discount' => $request->input('discount'),
            'total' => $request->input('total')
        ]);

        return redirect('/invoices');
    }

发票.php


    protected $fillable = ['invoice_no', 'invoice_date', 'due_date','sub_total','discount','total','customer_id'];

    public function item(){
        return $this->belongsToMany(Item::class,'invoices_items')->withPivot('quantity');;
    }

项目.php


    protected $fillable= ['name','sales_price','purchase_price', 'category_id'];


    public function invoices(){
        return $this->belongsToMany(Invoice::class, 'invoices_items')->withPivot('quantity');;
    }

我希望问题很清楚。谢谢你

【问题讨论】:

  • 使用attach() 方法。 -&gt;attach($itemId, ['quantity' =&gt; $quantity]);laravel.com/docs/8.x/…
  • 但是如何获得该特定项目的 $quantity 呢?我尝试使用 $request->input('quantity') 但它返回 null
  • 格式化你要发送到api的数据,例如items = [ ['itemId', 'quantity'], ['itemid', 'quantity'] ]你尝试了什么,你遇到了什么错误?
  • 我得到的数量不应该为空,当我尝试给数量一个值时,它仍然没有将所有项目 id 存储在数据透视表上

标签: php laravel vue.js


【解决方案1】:

在 Invoices 控制器中保存 Invoice 后,您应该使用与 attach() 的多对多关系,这里的项目到发票是您的操作方式。

public function store(Request $request)
    {     $invoice = Invoice::create([
            'invoice_no' => 'invoice',
            'invoice_date'=> $request->input('invoice_date'),
            'due_date'=> $request->input('due_date'),
            'customer_id'=> $request->input('customer_id'),
            'sub_total' => $request->input('sub_total'),
            'discount' => $request->input('discount'),
            'total' => $request->input('total')
        ]); 
$item = Item::findOrFail($request->get('item_id'));
    
    $item->invoices()->attach($invoice->primary_key, ['quantity' =>$request->get('quantity')]);

        return redirect('/invoices');
    }

【讨论】:

  • 它说:SQLSTATE[23000]:完整性约束违规:1048 列“数量”不能为空(SQL:插入invoices_itemsinvoice_iditem_idquantity)值(13, 3, ?))
  • 发票上是否有多个项目?如果是,那么您将需要迭代它们以获得准确的数量。这意味着selectedItem: { } 应该是一个列表selectedItems: []
  • 我改变了它,但仍然没有在数据透视表上保存数据。也没有显示任何错误
  • 不应该是$invoice->item()->atach()..吗?
  • 它可以从任何方向工作,无论是从发票还是项目方
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 2015-05-29
  • 2018-01-18
  • 2018-12-31
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2014-12-21
相关资源
最近更新 更多