【发布时间】:2019-02-22 16:11:27
【问题描述】:
我在使用 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。
【问题讨论】:
-
一条建议——如果你想得到一个只包含一列值的数组,你可以这样做: $idArray = DB::table("ratings")->where( "user", "=", Auth::user()->id)->where("story_id", "=", $o['story_id'])->lists('id');