我在使用 PHP Laravel 更新功能时遇到了一些问题。它不更新,只插入。
public function post_rate(){
$o = Input::all();
//has user already rated?!
$query = DB::table("ratings")->select("id")->where("user", "=", Auth::user()->id)->where("story_id", "=", $o['story_id'])->get();
foreach ( $query as $d):
$theID = $d->id;
endforeach;
if ( empty($query)): //User hasn't rated!
$z = new Rating();
else:
$z = new Rating($theID); //user has rated, tell which to update
-----------------------------^ that cause the problem!
endif;
$z->story_id = $o['story_id'];
$z->user = Auth::user()->id;
$z->rating = $o['rating'];
$z->save();
echo "OK";
}
它在没有创建行时起作用,但是当我使用 new Rating(@something) 时它会失败。
“ratings”表中的列 id 是 primary 和 auto_increment。
在我的模型中,我还设置了
public static $key = 'id';
输出“$theID”还包含 mysql 行的正确 ID。