[英]Laravel Call to undefined method
我正在嘗試更新數據庫中的數據,但始終出現錯誤。
調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: save()
這是我的代碼:
public function postTodo( Request $request ){
if ( $request->input('action') == 'set_as_done' ){
$thing = DB::Table('todo')->where('id', $request->input('id'));
if ( $thing ){
$thing->done = $request->input('set_as_done');
$thing->save();
}
return redirect(route('admin.todo'));
}
}
要執行$thing->save()
, $thing
必須是擴展Model
或Ardent
的model的實例。
當你做$thing = DB::Table('todo')->where('id', $request->input('id'));
$thing
變量是一個集合,與模型無關。
您必須為Thing.php
建立模型,然后可以執行以下操作:
$thing = Thing::where('id', $request->input('id'));
if ( $thing ){
$thing->done = $request->input('set_as_done');
$thing->save();
}
save方法適用於Eloquent模型,不適用於構建器,因此您的代碼需要觸發更新查詢而不是保存
我建議創建Eloquent模型,然后使用save()方法編寫代碼,這比使用builder更有意義
public function postTodo( Request $request ){
if ( $request->input('action') == 'set_as_done' ){
$thing = DB::table('todo')->where('id', $request->input('id'))->first();
if ( $thing ){
DB::table('todo')->where('id', $request->input('id'))->update([
'set_as_done' => $request->input('set_as_done')
]);
}
return redirect(route('admin.todo'));
}
}
我建議您使用php artisan make:model TodoModel為表todo創建模型。
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Todo extends Model{ protected $table = 'todo'; }
之后,您可以使用Todo保存數據。
public function postTodo( Request $request ){
if ( $request->input('action') == 'set_as_done' ){
$thing = Todo->find('id', $request->input('id'));
if ( $thing ){
$thing->set_as_done = $request->input('set_as_done')
$thing->save();
}
return redirect(route('admin.todo'));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.