我有这段代码,这段代码工作正常,数据已成功存储到表“reports”中。但我也想更新 Users 表及其字段 Credits。我怎样才能在这个功能中做到这一点?我也有这两个表“reports”和“users”之间的关系。
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');
最佳答案
您只需添加更新用户的逻辑(假设您有一个名为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();
}
关于php - 拉拉维尔。在一个 POST 方法中更新两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366305/