我遇到了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";
}
当没有行时它可以工作,但是当我使用新的Rating(@something)时它会失败。
"ratings"表中的id列是主键和自动递增的。
在我的模型中,我也设置了
public static $key = 'id';
输出"$theID"还包含了mysql行的正确ID。