我有这个代码,这段代码工作正常,数据成功存储到表"报告"。但我也想更新Users表及其字段Credits。我怎么能在这个功能中做到这一点?我也有这两个表格之间的关系"报告"和"用户"。
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
$report->save();
return redirect()->back();
}
用户表
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->integer('credits');
$table->enum('role', ['user', 'admin'])->default('user');
$table->rememberToken();
$table->timestamps();
});
报告表
Schema::create('reports', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('credits');
答案 0 :(得分:1)
您只需要添加逻辑来更新用户(假设您有一个名为user
的关系方法):
public function giveCredits($id)
{
$report = Report::where('id', $id)->first();
$report->credits += Input::get('credits');
// if the report has a user, update it
if ($report->user) {
$report->user->credits += Input::get('credits');
$report->user->save();
}
$report->save();
return redirect()->back();
}