感謝您的幫助金字塔先生。這裏是代碼:
public function update(Request $request, $id)
{
$invoice = Invoice::findOrFail($id);
$invoice->invoice_no = $request->invoice_no;
$invoice->client = $request->client;
$invoice->title = $request->title;
$invoice->client_address = $request->client_address;
$invoice->invoice_date = $request->invoice_date;
$invoice->due_date = $request->due_date;
$invoice->subtotal = $request->subtotal;
$invoice->grandtotal = $request->grandtotal;
$invoice->save();
$products = $request->all();
$name = $products['name'];
$price = $products['price'];
$qty = $products['qty'];
$total = $products['total'];
foreach($name as $key => $n) {
$invoice->products()->update([
//=> $invoice->id,
'name' => $name[$key],
'price' => $price[$key],
'qty' => $qty[$key],
'total' => $total[$key]
]);
}
Session::flash('success', 'Invoice Updated');
return redirect()->route('invoices');
}
與此準確的代碼,我可以創建和工作正常,但如果我用它來更新它不會讓我。
數據庫
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_no');
$table->date('invoice_date');
$table->date('due_date');
$table->string('title');
$table->string('client');
$table->string('client_address');
$table->decimal('subtotal');
$table->decimal('grandtotal');
$table->timestamps();
});
產品
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('invoice_id')->unsigned();
$table->string('name');
$table->string('qty');
$table->string('price');
$table->string('total');
$table->timestamps();
});
關係
class Invoice extends Model {
protected $fillable =['client','client_address','title','invoice_no','invoice_date','due_date','discount', 'subtotal','grandtotal'];
public function products(){
return $this->hasMany('App\Product', 'invoice_id');
}
}
class Product extends Model
{
protected $casts = [
'name' => 'array',
'price' => 'array',
'qty' => 'array',
'total' => 'array'
];
protected $fillable = ['invoice_id','price','qty','total','name'];
public function invoice(){
return $this->belongsTo('App\Invoice');
}
}
謝謝
你究竟想要做什麼或實現什麼?此外,所提供的代碼似乎不完整且不清楚。請再展示一些代碼。 –
邏輯中存在一個問題,'$ name'只是一個字符串!或不 ?和錯誤說'... save()必須是給定的Model數組的實例'所以你應該通過一個模型來保存()而不是數組! – Maraboc
它清楚我想要達到的目標。馬拉博克,試圖通過一種模式來保存和不工作。我知道邏輯是錯誤的,只是不知道如何解決,因爲我是laravel的新手。謝謝 –