我正在尝试更新发票中的项目,删除项目或添加项目时需要和问题,如果我删除所有更新的项目,我需要帮助,请
我收到错误消息:“ SQLSTATE [42S22]:找不到列:1054”字段列表”中的未知列“ product”(SQL:更新invoice_product
设置了id
= 27,invoice_id
= 29,product_id
= 3,unit_price
= 80,qty
= 1,created_at
= 2018-10-08 16:54:53,updated_at
= 2018 -10-08 16:54:53,deleted_at
=,product
= 3,其中invoice_id
= 29和id
= 27)“
发票表
项目表
id
商品代码
item_desc
单价
invoice_items表
发票编号
item_id
单价
数量
发票模型
public function items()
{
return $this->hasMany(InvoiceProduct::class, 'invoice_id');
}
我的控制器更新
$invoice = Invoice::findOrFail($id);
$items = [];
$itemIds = [];
$subTotal = 0;
foreach($request->items as $item) {
if(isset($item['id'])) {
InvoiceProduct::where('invoice_id', $invoice->id)
->Where('id', $item['id'])
->update($item);
$itemIds[] = $item['id'];
$item ='please re add items';
} else {
$items[] = new InvoiceProduct($item);
}
$subTotal += $item['unit_price'] * $item['qty'];
}
$data = $request->except('items');
$data['sub_total'] = $subTotal;
$data['total'] = $data['sub_total'] - $request->discount;
$invoice->update($data);
InvoiceProduct::whereNotIn('id', $itemIds)
->where('invoice_id', $invoice->id)
->delete();
if(count($items)) {
$invoice->items()->saveMany($items);
}
return response()
->json(['saved' => true, 'id' => $invoice->id]);
}
答案 0 :(得分:1)
由于这是Many to Many
关系。您的关系应该为belongsToMany()
。
模型关系
class Invoice extends Model
{
public function items()
{
return $this->belongsToMany(Item::class)
->withPivot(['unit_price', 'qty']);
}
}
class Item extends Model
{
public function invoices()
{
return $this->belongsToMany(Invoice::class)
->withPivot(['unit_price', 'qty']);;
}
}
处理数据
public class InvoiceControler extends Controller
{
public function store(Request $reques)
{
// save the invoice
$invoice = Invoice::create([
...
]);
// save invoice-items
foreach($request->items as $item) {
$invoice->intems()->attach($item['id'], [
'unit_price' => $item['unit_price'],
'qty => $item['quantity']
]);
}
}
public function update(Request $request, Invoice $invoice)
{
// update the invoice with new request data.
$invoice->update([
...
]);
// items to be synchronize
// $items = [];
// create an item array to synchronize
foreach($request->items as $item) {
array_set($items, $item['id'], [
'unit_price' = $item['unit_price],
'qty' = $item['qty']
]);
}
// synchronize items.
$invoice->items()->sync($items);
}
}