如何在 Laravel 4 中更新字段的列


How to update a column of a field in Laravel 4?

我正在尝试在用户控制器中调用此函数updateImpression()的路由上调用AJAX请求,并且此函数尝试在存储在MySQL中的"users"表中增加名为"impressions_cpunt"的计数器列。我尝试使用Eloquent仅更新一个特定用户的列。

public function updateImpression()
{
    $username = Input::get('username');
    $user = User::where('username', '=', $username)->first();
    $impressions_count = $user->impressions_count + 1;
    // save() method failed to update my database.
    // $user->impressions_count = $impressions_count;
    // $user->save();
    //update() method does not return anything. Any syntax error here?
    //$user->update(array('impressions_count' => $impressions_count));
    DB::table('users')
        ->where('username', $username)
        ->update(array('impressions_count' => $impressions_count));
    $user = User::where('username', '=', $username)->first();
    return $user->impressions_count;
}

我认为 save() 函数首先应该工作,但我的数据库没有得到更新并返回原始计数,并且 update() 函数甚至没有从函数返回任何值。这仅在我使用 DB 时才有效,但我认为 Eloquent 应该更好用,因为这是 Laravel。我错过了什么或语法有问题吗?我知道应该使用increments()数据类型,但请允许我在更改任何内容之前解决此问题。

更新:这是我使用 save() 方法时在调试栏中显示的数据库查询:

select * from 'users' where 'username'= <test> limit 1
select count(*) as aggregate from 'users' where 'username'= <test>
select count(*) as aggregate from 'users' where 'email'= <test@example.org>

用户对象(应该是 Eloquent 子对象)像任何其他实体一样,如果您的 save() 调用成功,则会在更改后存储其状态。因此,无需显式更新记录。在您的情况下,我会选择这样的东西:

public function updateImpression()
{
    $username = Input::get('username');
    $user = User::where('username', '=', $username)->first();
    $user->impressions_count += 1;
    $user->save();
    return $user->impressions_count;
}

在 Laravel 5.2 中,您可以使用以下 Eloquent 构建器更新特定列:

public function update(Request $request, $id) {
    $user = User::where('id', $id)->update(['name', $request->name]);
    return redirect()->back()->with('status', trans('User has been updated successfully.'))
}