感谢您的帮助金字塔先生。这里是代码:
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的新手。谢谢 –