php - 拉拉维尔。在一个 POST 方法中更新两个表

标签 php mysql laravel

我有这段代码,这段代码工作正常,数据已成功存储到表“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/

相关文章:

拉拉维尔。如何获取数据库通知的ID?

php - Laravel 5.4 - 在哪里更改登录过程

php - Laravel 5 - 多语言网站(LTR 和 RTL)

javascript - Laravel jQuery AJAX 实时搜索

python - 将 python int 解析为 Mysql unsigned TINYINT

MySQL varchar 默认为 0 而不是空字符串

php - 我需要清理用户输入的 Laravel 吗?

php - 日期格式无法正常工作

mysql - ActiveRecord 在 Ruby 1.9.2-rc1 下以 ASCII-8Bit 返回数据

php - laravel 中 https 的问题